How to get multiple files in one key in rails? - javascript

I want to parse multiple files in one key in the Rails API.
and this is rails controller code.
def fun
render json: params[:file]
end
and this is javascript-jQuery code.
var form = new FormData();
form.append("file", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("file", fileInput.files[0], "75380217_961903127500586_7366878762530504704_n.jpg");
var settings = {
"url": "http://127.0.0.1:3000",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});
and this is response
{
"tempfile": "#<File:0x00007fe4c4a289f0>",
"original_filename": "75380217_961903127500586_7366878762530504704_n.jpg",
"content_type": "image/jpeg",
"headers": "Content-Disposition: form-data; name=\"file\"; filename=\"75380217_961903127500586_7366878762530504704_n.jpg\"\r\nContent-Type: image/jpeg\r\n"
}
what can I do?

Give the params unique names so that they don't just overwrite each other in the params hash:
form.append("file", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("other_file", fileInput.files[1], "75380217_961903127500586_7366878762530504704_n.jpg");
Or create an array in the params:
form.append("files[]", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("files[]", fileInput.files[1], "75380217_961903127500586_7366878762530504704_n.jpg");
Or a hash:
form.append("files[first]", fileInput.files[0], "75341083_406717103617108_7315677611286331392_n.jpg");
form.append("files[second]", fileInput.files[1], "75380217_961903127500586_7366878762530504704_n.jpg");

Related

Replace parts of a JSON object with HTML input values

I recently tested A LOT of different syntax for sending an ajax post request, and the only one which actually worked was the one I got from my Postman testing. The only problem I have now is the Postman code snippet is "hardcoded" and features a weird string syntax I have never seen before. I want to replace parts of that weird string with values from HTML inputs. Any ideas how I can achieve this?
I have two simple HTML inputs:
<input type="text" id="username" name="username" placeholder="Username" autofocus />
<input type="password" id="password" name="password" placeholder="Password" />
And here is the part I got from Postman (JavaScript):
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": "{ \r\n\"Username\":\"username123\",\r\n\"Password\":\"password123\"\r\n}"
}
$.ajax(settings).done(function(response) {
console.log(response);
});
Specifically, the part I'm asking about is the "data" line. I want to be able to take the values from the two HTML inputs, and replace "username123" and "password123" with them respectively. I have tried playing around with the data string, like removing \r\n and some " and \ , but then I get an error from the API I'm trying to call to. Do I really need all those? To be clear, I'm wondering how to put my variables into the string using valid syntax, not how to get the values like for example:
var usname = document.getElementById("username").val();
or
var usname = $('#username').val();
And these JSON syntax are tested and recieves an error:
"data": {"Username": "username123","Password": "password123"}
"data": "{"Username": "username123", "Password": "password123"}"
"data": {"Username": usname, "Password": pword}
"data": {"Username": $('username').val(), "Password": $('password').val()}
I feel like at least the first one should work, but it just comes back with error 500. For reference, here's what the body (data) looks like in Postman (working):
{
"Username":"username123",
"Password":"password123"
}
Could it be an issue with whitespace or something? I sadly don't have access to the source code of the API I'm calling.
I'm wondering how to put my variables into the string using valid
syntax
settings.data = settings.data.replace("username123", usname);
settings.data = settings.data.replace("password123", uspassword);
For formatting the data as JSON and the be able to use its properties for different purposes:
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": "{ \r\n\"Username\":\"username123\",\r\n\"Password\":\"password123\"\r\n}"
};
//remove line breaks
settings.data = settings.data.replace('/\r?\n|\r/', '');
//convert to properties
settings.data = JSON.parse(settings.data);
//re-assign properties as needed
settings.data.Username = 'newUsername';
settings.data.Password = document.getElementById('password').value;
console.log(settings.data);
<input type="password" id="password" name="password" placeholder="Password" value="newPassword"/>
I suggest to use a FormData to wrap the data you are going to send:
var formData = new FormData();
formData.append('Username', $("#username").val());
formData.append('Password', $("#password").val());
And later, you call the ajax post like this:
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"contentType": 'application/x-www-form-urlencoded',
"processData": false,
"data": formData
};
$.ajax(settings).done(function(response)
{
console.log(response);
});
If you need to send data as JSON then you can give a try to next code:
var data = {};
data.Username = $("#username").val();
data.Password = $("#password").val();
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": JSON.stringify(data)
};
$.ajax(settings).done(function(response)
{
console.log(response);
});

ClientId is null when calling ValidateClientAuthentication with Ajax

I have the following code that are generated by POSTMAN:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:51734/token",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"cache-control": "no-cache",
"Postman-Token": "2879f786-3b1f-42fe-8198-b2193764d165"
},
"data": {
"grant_type": "client_credentials",
"client_id": "6E1JIQDEF0M"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When you run the code above, the following code below are first executed:
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId = string.Empty;
string clientSecret = string.Empty;
ClientDTO client = null;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
context.TryGetFormCredentials(out clientId, out clientSecret);
}
if (context.ClientId == null)
{
//Remove the comments from the below line context.SetError, and invalidate context
//if you want to force sending clientId/secrects once obtain access tokens.
context.Validated();
//context.SetError("invalid_clientId", "ClientId should be sent.");
//return Task.FromResult<object>(null);
return;
}
}
The problem I have is that context.ClientId is always null, and I don't know why.
When I make the same request with C# it works:
var client = new RestClient("http://localhost:51734/token");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "db182d32-9eff-4150-815e-2fd7d10ebd58");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "grant_type=client_credentials&client_id=6E1JIQDEF0M&undefined=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
So why does it work with c# but not javascript? Anyone who has any idea?
Try to call like this from Javascript.
data : 'grant_type=client_credentials&client_id=6E1JIQDEF0M'

javascript send local file to api

I'm developing an electron app which must call an api to replace (update) file X in server by file Y which is in my computer.
The user download file X from Server in order to edit it, (this file will be named file Y in my computer).
When the user finish to edit file Y, i check if both files X and Y are differents and i call the api in order to replace file X by file Y. I don't need to put file Y in a form before calling api, i want to do it without form.
Only my request payload is different from what i expect to have, there is no problem in my request headers
I expect to have something like that
and i get this
Here is what i do
const fs = require('fs');
let fileY = fs.readFileSync(path.resolve('gitignore.txt'));
let form = new FormData();
form.append("type", "jur_document");
form.append("file", fileY, 'gitignore.txt');
form.append("saveActionType", "SAVEMAJOR");
form.append("attributes", "MIMETYPE=text/plain");
let settings = {
"async": true,
"url": `${Constante.URL}/documents`,
"method": "POST",
"type": "POST",
"headers": {
// "Content-Type": "text/plain",
"Authorization": sessionStorage.getItem('authorization')
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
};
$.ajax(settings)
.done((response) => {
console.log(response);
}).fail(err => {
console.log(err);
});
}
i finally get the solution
I read my file and create a blob which i use to recreate my file
const fs = require('fs');
let buffer = fs.readFileSync(`${app.getAppPath()}/test.txt`);
let fileY = new File([new Uint8Array(buffer)], 'test.txt', {
type: 'text/plain'
});
form.append("file", fileY);
and here is ajax settings
let settings = {
"url": `${Constante.URL}/documents`,
"type": "POST",
"headers": {
"Authorization": sessionStorage.getItem('authorization')
},
"processData": false,
"contentType": false,
"data": form
};

github says cannot parse json while creating a repo in rest api

I'm learning REST api for github and trying to create a new repository by running a JS. Here is my function for creating a new repo: the token is generated, and all access/scopes is granted for my token.
function createNewRepo(userId, name){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": "EnableIssues",
"content-type": "application/json",
"Authorization": token,
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true,
}
};
//console.log(eval(options));
request(options, function (error, response, body)
{
var obj = JSON.parse(body);
console.log( obj );
});
}
however when running this, I find,
{ message: 'Problems parsing JSON', documentation_url: 'https://developer.github.com/v3' }
I'm not sure how exactly could the JSON be invalid.
Also, the documentation says it must include public_repo or repo which I'm also not sure how to apply here.
This for me has created the repository.
var myToken = "token INSERTHERETHETOKEN"; // <-- there must be the word token before the actual token.
var urlRoot = "https://api.github.com";
var request = require("request");
function createNewRepo(user, name, token){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": user,
// "content-type": "application/json", This is set by json:true
"Authorization": token,
"Accept": "application/vnd.github.v3+json"
},
body: {
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true
},
json: true
};
request(options, function (error, response, body) {
// Do your stuff... but notice that response
// is already a json object and you don't need to parse it.
});
}
createNewRepo("YourGithubUser", "test.repository", myToken);

Upload Image by ajax gives unsupported media type error

I am trying to upload an image to my server using jquery. I need to send image, filename and file url to backend. There for I have added these three fields in "data" (refer code). I am doing it like this(below code) but I am getting error in console saying "unsupported media file" 415. How should I solve it?
posterFile = e.target.files;
selectedPoster = posterFile[0];
uploadPoster() {
var blobPosterFile = selectedPoster;
console.log("U called me?")
var formData = new FormData();
formData.append("fileToUpload", blobPosterFile);
var that = this;
let token;
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.backend.example.name.com/api/v1/videos/",
"method": "POST",
processData: false,
contentType: false,
"credentials": 'include',
"headers": {
Authorization: "Token " + that.props.token_Reducer.token
},
"data": {
"Title": selectedFile.name,
"File": videoURL,
"Poster": formData
},
success:( response, textStatus, jQxhr )=> {
console.log("poster uploaded")
}
}
$.ajax(settings).done((response) => {
});
}
I am getting error saying "unsupported media type" 415

Categories

Resources