gpt4 book ai didi

javascript - 在 Postman 上使用 Ajax 上传文件,但在浏览器上不工作

转载 作者:行者123 更新时间:2023-11-30 09:17:25 25 4
gpt4 key购买 nike

我正在尝试让某些用户使用 Ajax 将视频上传到 API。这适用于 Postman,但是当从浏览器执行此操作时,我收到 500 内部服务器错误。

我没有访问服务器的权限,所以我无法显示服务器日志,但据那个人说,他收到了“OPTIONS”帖子,但没有收到带有 multipart/form-data 的第二个帖子。 .当我在 chrome 网络工具中检查我的表单数据时,它给了我 this .

我为每次上传附加的 url 看起来像 this .

The two requests in the network tool.

我的表单的发布方式似乎有问题,我很确定这是我的错,而不是服务器的错,因为它与 Postman 一起工作。

postman 代码是:

var form = new FormData();
form.append("video", "C:\\Users\\Sidhant\\Downloads\\examplevid.mp4");

var settings = {
"async": true,
"crossDomain": true,
"url": "https://apiurl/catagoryid/videotitle",
"method": "POST",
"headers": {
"Authorization": "Bearer token",
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"Postman-Token": "token"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}

$.ajax(settings).done(function (response) {
console.log(response);
});

除了获取文件的方式不同,我的代码是一样的:

var fileinput = document.getElementById("fileinput").files[0];
var form = new FormData($('#fileinput')[0]);

使用 postman 将视频添加到 API,而通过浏览器则出现 500 错误。我怎样才能停止收到此错误,我可以尝试哪些操作。我是 Ajax 的初学者,所以我不熟悉这类问题。

最佳答案

问题在于您如何在表单数据中选择文件。

var fileinput = document.getElementById("fileinput").files[0];
var form = new FormData($('#fileinput')[0]);

您使用普通 js 正确选择了文件,但随后使用 Jquery 并简单地选择了文件输入元素。所以这就像您试图附加 html 元素本身,而不是用户数据。

使用这个。

//null check on the input 
var fileinput = $('#fileinput').length ? $('#fileinput')[0].files[0] : null;
//Create the FormData and add the file to the FD
var form = new FormData();
form.append('video', fileinput );

关于javascript - 在 Postman 上使用 Ajax 上传文件,但在浏览器上不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com