javascript multipart/formdata 不使用 jQuery.ajax 发送文件数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20696464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:02:23  来源:igfitidea点击:

multipart/formdata is not sending file data with jQuery.ajax

javascriptjqueryajaxdjangoapi

提问by Zach Shallbetter

I have an endpoint from our Django backend guys with documentation that reads:

我有一个来自我们的 Django 后端人员的端点,其文档如下:

POST to /api/1/photo-uploads/ with enctype="multipart/form-data" with files in field called "files[]".

使用 enctype="multipart/form-data" POST 到 /api/1/photo-uploads/,字段中的文件名为 "files[]"。

I've been attempting to send uploaded files with formData using jquery's AJAX method. I continue to get an error indicating that the file was not sent. When I view the payload I see.

我一直在尝试使用 jquery 的 AJAX 方法发送带有 formData 的上传文件。我继续收到一条错误消息,指出文件未发送。当我查看有效载荷时,我看到了。

undefined
------WebKitFormBoundary9AzM2HQPcyWLAgyR
Content-Disposition: form-data; name="file"; filename="auzLyrW.jpg"
Content-Type: image/jpeg

Which doesn't necessarily mean that it hasn't sent but there certainly isn't a location being posted. And I don't have any kind of verification that the file is uploaded.

这并不一定意味着它没有发送,但肯定没有发布位置。而且我没有任何形式的文件上传验证。

    var formData = new FormData();
    formData.append('file', $('#file-upload').get(0).files[0]);
    $.ajax({
        url: '/api/1/photo-uploads/',
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
    });

When I console.log formDatait simply show's the prototype methods like .append. So I'm unable to verify if the file's data is being sent beyond checking the payload. I can log $('#file-upload').get(0).files[0]but I only see details from the file itself. Because I'm testing it locally an upload location should be something like localhost:8000/.

当我 console.logformData它只是显示原型方法,如.append. 因此,除了检查有效负载之外,我无法验证文件的数据是否正在发送。我可以登录,$('#file-upload').get(0).files[0]但我只能看到文件本身的详细信息。因为我是在本地测试它,所以上传位置应该类似于 localhost:8000/。

The backend guys are under the impression that it's something I'm doing. When I do a simple form post it works fine. I've tried a number of plugins and basic methods and all have produced the 400 {"message": "No photos supplied.", "success": false}

后端人员的印象是这是我正在做的事情。当我做一个简单的表单发布时,它工作正常。我已经尝试了许多插件和基本方法,并且都产生了400 {"message": "No photos supplied.", "success": false}

Any ideas would be appreciated.

任何想法,将不胜感激。

回答by Zach Shallbetter

The documentation asked that it be called files[]. What was being sent was file.

文档要求将其称为files[]. 正在发送的是file.

formData.append('files[]', $('#file-upload').get(0).files[0]);

formData.append('files[]', $('#file-upload').get(0).files[0]);