Upload form data fails with axios - javascript

I have a form with multiple fileds, which one is a file input. I use axios to upload the file under a separate attribute:
axios.post(ENDPOINT,{
form: formData,
image: image
}, getAuthorizationHeader())
function getAuthorizationHeader() {
return {
headers: {
'Authorization': //...,
'Content-Type': undefined
}
};
}
formData is created like this:
let formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('amount', values.amount);
And the image is:
Under the network tab of the Chrome Dev tool, When I look at the request, it looks like this:
As you can see in the screenshot, the file is empty? The CONTENT-TYPE is application/json which is not what I expected. I expected browser to detect the CONTENT-TYPE as multipart/form-data
What is wrong here?

First of all, image should be part of the formData:
formData.append('image', <stream-of-the-image>, 'test.png')
Secondly, formData should be the second parameter of axios.post:
axios.post(ENDPOINT, formData, getAuthorizationHeader())
Last but no least, you should merge formData.getHeaders():
function getAuthorizationHeader() {
return {
headers: Object.assign({
'Authorization': //...,
}, formData.getHeaders())
};
}
Sample code for your reference: https://github.com/tylerlong/ringcentral-js-concise/blob/master/test/fax.spec.js

Related

Request in javascript (from python)

I have attempted to create a request in javascript, that has previously worked using python just fine.
the following is an accurate representation of the code I used to post the request with python:
url = 'https://website.com/api/e1'
header = {
'authorization': 'abcd1234'
}
payload = {
'content': "text",
}
r = requests.post(url, data=payload,headers=header )
This (above) works just fine in python.
now what I did in javascript is the following:
payload = {
"content": "this is text",
};
fetch("https://website.com/api/e1", {
method: "POST",
headers: {
"authorization":
"abcd1234",
},
body: JSON.stringify(payload),
});
but this is returning the error
400- Bad request
When using data parameters on python requests.post, the default Content-Type is application/x-www-form-urlencoded(I couldn't find it on the document, but I checked the request. If you know, please leave a comment).
To achieve the same result with fetch, you must do as follows.
const payload = {
'content': 'this is text',
};
fetch('https://website.com/api/e1', {
method: 'POST',
headers: {
'authorization': 'abcd1234',
},
body: new URLSearchParams(payload),
});
You don't need to do this body: JSON.stringify(payload), rather you can simply pass payload in body like this body:payload

Exporting formData from React to Spring boot backend

React code for build jsonBlob object
function jsonBlob(obj) {
return new Blob([JSON.stringify(obj)], {
type: "application/json",
});
}
exportFTP = () => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData));
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data",
},
});
};
Spring boot backend that accepts for frontend request
public class UploadFile {
#Autowired
private FTPClient con;
#PostMapping("/api/auth/uploadfiles")
public String handleFileUpload(#RequestParam("file") MultipartFile file) {
try {
boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());
System.out.println(result);
} catch (Exception e) {
System.out.println("File store failed");
}
return "redirect:/";
}
I want to figure out when I called the function from the frontend it's working properly but I change the state its doesn't send the object to the backend while the file appears in the directory. if I delete the file then only send it again and save it on the directory.
How I save multiple files while doesn't delete the previous ones
Thank you very much for your time and effort.
"Content-Type": "multipart/form-data",
Don't set the Content-Type yourself when posting a FormData.
The Content-Type needs to contain the boundary value that's generated by a FormData(example: multipart/form-data; boundary=----WebKitFormBoundaryzCZHB3yKO1NSWzsn).
It will automatically be inserted when posting a FormData instance, so leave this header out.
When you append blobs to a formdata then it will default the filename to just "blob"
On the backend you seems to override the file all the time:
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Generate a new unik name if you want to keep all files
of topic but why not go with the fetch api? Smaller footprint. don't require a hole library...
fetch('http://localhost:8080/api/auth/uploadfiles', {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json ,text/plain, */*'
}
})
In React application I used props to pass the file name from a different state and make sure to remove,
"Content-Type": "multipart/form-data",
Main function in React,
exportFTP = ({props from different state}) => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData),{You can use this parm for pass name});
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*"
},
});
};
And back end code I used same to get the original name then Its appears with the right name.
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Chears !!

Corrupted files when uploading to Dropbox via Ajax

I'm trying to use the Dropbox API to send files to a specific Dropbox folder via a web interface using Ajax.
Here is my code:
function UploadFile(token, callback) {
var fileName = $('input[type=file]')[0].files[0].name,
fileData = new FormData($('#file-upload')[0]),
dbxHeaderParams = {
'path': '/' + fileName,
'mode': { '.tag': 'add' },
'autorename': true
};
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/octet-stream',
'Dropbox-API-Arg': JSON.stringify(dbxHeaderParams)
},
data: fileData,
processData: false,
contentType: false,
success: function(result) {
console.log('NICE BRO');
callback();
},
error: function(error) {
console.error(error);
callback();
}
});
}
This code works: files are uploaded to my Dropbox folder and i can open them. They even have the right name and (almost) the right size. But the problem is that they are all corrupted because some lines are added during the process.
Here is an example: if I want to upload a .txt file containing this:
harder better faster stronger
Once uploaded on my Dropbox, it will looks like this:
-----------------------------2308927457834
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
harder better faster stronger
-----------------------------2308927457834--
I assume this is why I can't open files like images. I've tried several solutions but none of them can solve this. What am I doing wrong ? Thanks !
Seeing the relevant pieces of the HTML would be useful, but it looks like the issue is that you're supplying a FormData object to the upload call, as opposed to the File.
Try replacing this line:
fileData = new FormData($('#file-upload')[0]),
with this:
fileData = $('input[type=file]')[0].files[0],

Angular JS multi file upload request rejected in firefox

We have a multi file upload requirement and the approach is below. I am sending all the requests as below and it works fine normally. However when tried with around 10 files with couple of them more than 10MB in Firefox only request gets rejected.enter image description here
(function (i) {
var formData = new FormData();
formData.append('file', $scope.files[i]);
$http.post('yourUrl', formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function () {
// ...
});
}(i);
"Request error:" Object { data: null, status: 0, headers: Xc/<(), config: Object, statusText: "" } angular.min.js:103:49
e/<() angular.min.js:103
.responseError() <myname>Service.js:59
f/<() angular.min.js:112
Pe/this.$get</l.prototype.$eval() angular.min.js:126
Pe/this.$get</l.prototype.$digest() angular.min.js:123
Pe/this.$get</l.prototype.$apply()
I spent lot of time but didnt get any solution.

get file from filepath in javascript

I want to send my form(which will have file and name in it) using javascript to the server using http.post request but I am not able to fetch file in javascript. How will i do that i have file path. And i don't want to do this using input tag.
var Form = new FormData();
Form.append("file", file);//this file has to added using path of the file
$http.post(url, Form, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function(d) {
console.log("sucess" + d);
});

Categories