在FormData内部的文件的Ajax调用中出现错误404(未找到) [英] Error 404 (not found) in ajax call with file inside FormData

查看:469
本文介绍了在FormData内部的文件的Ajax调用中出现错误404(未找到)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用PHP脚本以通过Ajax上传文件.

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);
  }
});

目前,PHP脚本仅显示接收到的文件数据

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

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

传递给ajax数据的文件"对象如下

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: ""…}

但是当调用ajax调用时,在检查窗口中出现以下错误

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)

这听起来很奇怪,因为当我直接浏览脚本路径时,它不会给出任何404响应. 如果我注释"contentType"参数,该错误消失,但是从PHP脚本收到的响应为null. 我想念什么?

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?

推荐答案

您需要指定所需的内容类型.如您在帖子中提到的,php文件具有

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');

所以,尝试更改它

 contentType: false,

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

这篇关于在FormData内部的文件的Ajax调用中出现错误404(未找到)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆