Error 404 (not found) in ajax call with file inside FormData

a 夏天 提交于 2019-12-24 19:24:56

问题


I'm trying to invoke a PHP script to upload a file via Ajax.

var fd = new FormData();
fd.append('file', file);
console.log(file);

var xhr = $.ajax({
  url: 'https://www.mywebsite.com/it/file/upload/',
  type: 'POST',
  dataType: 'json',
  data: fd,
  cache: false,
  contentType: false,
  processData: false,

  success: function(result, message, xhr)
  {
    console.log(result);
  }
});

For the moment, the PHP script simply displays the received file data

header('Content-Type: application/json');
echo json_encode($_FILES['file']);
die();

The "file" object passed to ajax data is the following

File {errors: 0, name: "wedding.jpg", lastModified: 1500572565619, lastModifiedDate: Thu Jul 20 2017 19:42:45 GMT+0200 (ora legale Europa occidentale), webkitRelativePath: ""…}

But when ajax call is invoked, in the inspect window I get the following error

jquery.min.js:4 POST https://www.mywebsite.com/it/file/upload/ 404 (Not Found)

It sounds very strange, since when I directly browse the script path, it doesn't give any 404 response. If I comment the "contentType" parameter the error disappears, but the received response from PHP script is null. What am I missing?


回答1:


You need to specify the content type to what is expected. As you mentioned in your post, the php file has

 header('Content-Type: application/json');

So, try changing it

 contentType: false,

to

 contentType: "application/json; charset=utf-8",  


来源:https://stackoverflow.com/questions/45257368/error-404-not-found-in-ajax-call-with-file-inside-formdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!