3

I've made it so far to upload file with django rest framework via terminal, Something like this:

curl -X POST -S -H -u -F "file=@image.jpg;type=image/jpg" http://127.0.0.1/upload.

But how can I use this command via javascript json? I get error like unsupported file code 415?

Can anybody help me out? Thanks

M.javid
  • 6,387
  • 3
  • 41
  • 56
Ezra P.
  • 91
  • 1
  • 1
  • 12
  • Can you explain a bit what u exactly want to do? – Navneet Jul 15 '15 at 11:06
  • I use django rest framework to communicate with phonegap to my backend Django. Now I want to upload file to use django rest framework. Via terminal it works. But I don't get it to use a standard form in the frontend and to upload via post JSON or something like that. – Ezra P. Jul 15 '15 at 11:10
  • This might help you http://stackoverflow.com/questions/20473572/django-rest-framework-file-upload – chandu Jul 15 '15 at 12:19
  • This is my backend: class FileUploadView(APIView): parser_classes = (JSONParser, MultiPartParser, FormParser,) def put(self, request, format='jpg'): print request.FILES up_file = request.FILES['file'] destination = open('/var/www/Test/media/' + up_file.name, 'wb+') for chunk in up_file.chunks(): destination.write(chunk) destination.close() return Response(up_file.name, status.HTTP_201_CREATED) – Ezra P. Jul 15 '15 at 12:54
  • This is my frontend: function upload(){ var photo = document.getElementById("upload"); var files = photo.files[0]; var ajaxRequest = $$.ajax({ type: "PUT", url: "http://127.0.0.1/upload", contentType: 'application/json', processData: false, file: files, }); } } – Ezra P. Jul 15 '15 at 12:58

1 Answers1

0
 function upload() {

  var photo = document.getElementById("upload");
  var file = photo.files[0];
  var xhr = new XMLHttpRequest();

  xhr.open("PUT", 'http://127.0.0.1/upload', true);
  xhr.setRequestHeader('Authorization', ' Token ' + JWT);
  xhr.setRequestHeader("Content-type", "multipart/form-data")
  xhr.setRequestHeader("X_FILENAME", file.name);
  xhr.send(file);

}
sudhansu63
  • 6,025
  • 4
  • 39
  • 52
Ezra P.
  • 91
  • 1
  • 1
  • 12
  • this was the solution. – Ezra P. Jul 15 '15 at 17:40
  • Welcome to Stack Overflow! While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. – Kevin Brown-Silva Jul 17 '15 at 16:19