I'm switching from Jquery AJAX to react-dropzone & Axios, I'd like to upload a file to my Django server, I have no issue posting a blob url of the image on the server but I want to get it under request.FILES but I am getting an empty queryset.
request.FILES : <MultiValueDict: {}> <!--- empty
request.POST : <QueryDict: {}> <!--- able to get a blob url
Here's what my axios configuration looks like :
const temporaryURL = URL.createObjectURL(step3.drop[0]);
var fd = new FormData();
fd.append('image', temporaryURL);
axios({
method: 'post',
url: SITE_DOMAIN_NAME + '/business-card/collect/',
data: fd,
headers: {
"X-CSRFToken": CSRF_TOKEN,
"content-type": "application/x-www-form-urlencoded"
}
}).then(function (response) {
console.log(response)
URL.revokeObjectURL(temporaryURL);
}).catch(function (error) {
console.log(error)
});
I am receiving the file on a classBasedView on POST request.
How can I upload the file? Where am I wrong?
Edit
I also tried "application/form-data", doesn't solve the problem
the problem came from the content-type as it was using "application/form-data" instead of "multipart/form-data".
I am answering in case, someone comes here by searching on google:
let formData = new FormData();
formData.append('myFile', file);
formData.append('otherParam', 'myValue');
axios({
method: 'post',
url: 'myUrl',
data: formData,
headers: {
'content-type': 'multipart/form-data'
}
}).then(function (response) {
// on success
}).catch(function (error) {
// on error
});
Related
I am uploading file in react using axios.
when I am doing
alert(values.attachedFile[0]);
but when I am sending values.attachedFile[0] in axios post request enpty thing is going.
const { result } = await axios.post(app.resourceServerUrl + '/file/upload', {
data: values.attachedFile[0],
headers: {
'Content-Type': 'multipart/form-data',
},
});
but as part of request is is going empty.
what mistake I am doing?
To upload file with axios you need to use FormData:
const formData = new FormData();
// ...
formData.append("data", values.attachedFile[0]);
axios.post(app.resourceServerUrl + '/file/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
I am trying to send a file and some json in the same multipart POST request to my REST endpoint. The request is made directly from javascript using axios library as shown in the method below.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
formData.append("document", documentJson);
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
However, the problem is when I inspect the request in chrome developer tools in the network tab, I find no Content-Type field for document, while for file field Content-Type is application/pdf (I'm sending a pdf file).
On the server Content-Type for document is text/plain;charset=us-ascii.
Update:
I managed to make a correct request via Postman, by sending document as a .json file. Though I discovered this only works on Linux/Mac.
To set a content-type you need to pass a file-like object. You can create one using a Blob.
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
Try this.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
// formData.append("document", documentJson); instead of this, use the line below.
formData.append("document", JSON.stringify(documentJson));
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
You can decode this stringified JSON in the back-end.
you only need to add the right headers to your request
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
header: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
})
You cant set content-type to documentJson, because non-file fields must not have a Content-Type header, see HTML 5 spec 4.10.21.8 multipart form data.
And there`s two way to achieve your goals:
JSON.stringify your data, and decode it in the back-end like this answer below
pass a file-like object and set Content-Type like this answer below
How to download zip file from reactjs using POST API.
The request is coming from nodejs in binary form
you can use jszip link https://github.com/Stuk/jszip like
import zipTargetFiles from '/path'
zipTargetFiles( data ).then(file => {
//operations
})
if you use fetch like this.
fetch('URL', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
//Body
})
}).then((response)=>{
//here is youu want zip data
var zip = new JSZip();
var zipData = response.data //
// Add an top-level, arbitrary text file with contents
zip.file("response.txt", zipData);
// Generate the zip file asynchronously
zip.generateAsync({type:"blob"})
.then(function(content) {
// Force down of the Zip file
saveAs(content, "zipFile.zip");
});
}).catch((error)=>{
console.log(error)
})
You can use JsZip on Client Side. Then, do a request with axios. Like this:
request = (currentUrl: string): Promise<void> => axios({
url: currentUrl,
method: 'GET',
responseType: 'blob',
}).then((response) => {
const url: string = window.URL.createObjectURL(new Blob([response.data]));
});
I am trying to send a file and some json in the same multipart POST request to my REST endpoint. The request is made directly from javascript using axios library as shown in the method below.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
formData.append("document", documentJson);
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
However, the problem is when I inspect the request in chrome developer tools in the network tab, I find no Content-Type field for document, while for file field Content-Type is application/pdf (I'm sending a pdf file).
On the server Content-Type for document is text/plain;charset=us-ascii.
Update:
I managed to make a correct request via Postman, by sending document as a .json file. Though I discovered this only works on Linux/Mac.
To set a content-type you need to pass a file-like object. You can create one using a Blob.
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
Try this.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
// formData.append("document", documentJson); instead of this, use the line below.
formData.append("document", JSON.stringify(documentJson));
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
You can decode this stringified JSON in the back-end.
you only need to add the right headers to your request
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
header: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
})
You cant set content-type to documentJson, because non-file fields must not have a Content-Type header, see HTML 5 spec 4.10.21.8 multipart form data.
And there`s two way to achieve your goals:
JSON.stringify your data, and decode it in the back-end like this answer below
pass a file-like object and set Content-Type like this answer below
I'm using React and Axios to post formData to an internal .NET API.
The API is expecting data like this:
[HttpPost("upload")]
public virtual async Task<IActionResult> PostMulti(Int64 parentId, ICollection<IFormFile> fileData)
{
foreach (var file in fileData) {
await SaveFile(file, parent);
}
return Created("", Map(Repository.Get(parentId)));
}
When I step through the debugger, the count for "fileData" is always 0.
Here is how I'm sending it using Axios:
const formData = new FormData();
formData.append('image', this.state.file);
console.log("this.state.file = ", this.state.file);
console.log("formData = ", formData);
axios({
url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
//handle success
console.log('response -- then: ', response);
this.setState({
file: this.state.file
});
})
.catch((response) => {
//handle error
console.log('response -- catch: ', response);
});
I use console.log for debugging. It shows me the file object when I write it out(name, size, etc).
It also fires in the ".then" handler of the method and shows this:
"response -- then: data: Array(0), status: 201, statusText: "Created"
"
So, I have no idea why it's not sending anything to the API and I don't really know what's happening or how to fix this problem.
Any help would be greatly appreciated.
Thanks!
You should post array of the formData
const filesToSubmit = []
filesToSubmit.push((new FormData()).append('image', this.state.file))
and while posting the data the property name should be formData
axios({
url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
method: 'POST',
data: {formData : filesToSubmit},
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
If there is an issue with constructing an array you need to add IFormFile properties to the array
So I had exactly the same issue, whereby no matter which way I twisted the FormData object and regardless of the headers I sent, I couldn't get .NET to accept the submission.
From the Node.js side, it was difficult to actually inspect the HTTP call issued by Axios - meaning I couldn't see what I was actually POSTing.
So I moved the POST to the UI for some debugging, and found that the FormData payload was not being passed as I was expecting, so it was proper that .NET was rejecting.
I ended up using the configuration below, and the POSTs began going through. Again, in my case, I thought I needed FormData, but the below was simple enough:
axios({
url: myUrl,
method: 'POST',
data: `email=${myEmail}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
Update: Not sure how encoded data will work, but since it'll be passed as a string, it's worth a shot!
const myUploadedImage = "data:image/png;name=colors.png;base64,iVBORw0KGgoAAAANSUhEUgAAA5gAAAEECAIAAADCkQz7AAAGGUlEQVR4nO3YIY/IcRzHcWd4AjZJkZQr2I1dIJlyRU5ErkJggg=="