Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I upload a file from Axios to Django?

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

like image 928
Hiroyuki Nuri Avatar asked Mar 22 '18 17:03

Hiroyuki Nuri


People also ask

How do I upload files to Django project?

Django provides built-in library and methods that help to upload a file to the server. The forms. FileField() method is used to create a file input and submit the file to the server. While working with files, make sure the HTML form tag contains enctype="multipart/form-data" property.

What is Axios Django?

Axios is a Javascript library used to make HTTP requests from Node. js or XMLHttpRequests from the browser. It is a lightweight HTTP client based on the XMLHttpRequests service. It is similar to the Fetch API and is used to perform HTTP requests.


1 Answers

the problem came from the content-type as it was using "application/form-data" instead of "multipart/form-data".

like image 109
Hiroyuki Nuri Avatar answered Oct 13 '22 14:10

Hiroyuki Nuri