Javascript/jQuery 附加到 FormData() 返回“未定义”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26340985/
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-08-22 22:45:45  来源:igfitidea点击:

Javascript/jQuery Append to FormData() returns 'undefined'

javascriptjqueryhtml

提问by Mark Sandman

I'm trying to do a simple file upload using jQuery. I have a file input in my HTML like so:

我正在尝试使用 jQuery 进行简单的文件上传。我的 HTML 中有一个文件输入,如下所示:

<form id="PhotoUploadForm" action="/some/correct/url" method="post" enctype="multipart/form-data">
            <input type="file" id="uploadPhoto" accept="image">
</form>

I also have some JavaScript / jQuery bound to the change event of the input, like so:

我还有一些 JavaScript / jQuery 绑定到输入的更改事件,如下所示:

   $('#uploadPhoto').on("change", function (event) {

        var fileData = this.files[0];
        var data = new FormData();
        data.append('image',fileData);
        data.append('content','What could go wrong');
        console.log(data.image, data.content); // this outputs 'undefined undefined' in the console

        $.ajax ({
            url: "/some/correct/url",
            type: 'POST',
            data: data,
            processData: false,
            beforeSend: function() {
               console.log('about to send');
            },
            success: function ( response ) {                   
                console.log( 'now do something!' )
            },
            error: function ( response ) {
                console.log("response failed");
            }
        });
    });

I noticed I was getting a 500 error! Most likely the data is incorrect, I know the URL is good. So I tried to output the data to the console and I noticed that my data appends return 'undefined'

我注意到我收到了 500 错误!很可能数据不正确,我知道 URL 是好的。所以我试图将数据输出到控制台,我注意到我的数据附加返回 ' undefined'

console.log(data.image, data.content); // this outputs 'undefined undefined' in the console

when I console.log(data) I get the following:

当我 console.log(data) 我得到以下信息:

FormData {append: function}__proto__: FormData

Am I doing something wrong here? Why are data.image& data.contentundefined? When I output the this.files[0]I get the following:

我在这里做错了吗?为什么是data.image&data.content未定义?当我输出时,this.files[0]我得到以下信息:

File {webkitRelativePath: "", lastModified: 1412680079000, lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST), name: "2575-Web.jpg", type: "image/jpeg"…}lastModified: 1412680079000lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST)name: "2575-Web.jpg"size: 138178type: "image/jpeg"webkitRelativePath: ""__proto__: File

So the issue isn't with the image. Am I correct?

所以问题不在于图像。我对么?

回答by Marco Bonelli

Issue

问题

You are misunderstanding the FormDataobject. A FormDataobject has only an .append()method, which doesn't append properties to it, but only stores the data provided. Hence, obviously, the .imageand .contentproperties will be undefined.

你误解了FormData对象。一个FormData对象只有一个.append()方法,它不向它附加属性,而只存储提供的数据。因此,显然,.image.content属性将是未定义的。

If you want to create a object with the .imageand .contentproperties you should instead create a regular object and then send it.

如果您想创建一个具有.image.content属性的对象,您应该创建一个常规对象然后发送它。

Workaround

解决方法

To achieve what you want you have some options:

为了实现你想要的,你有一些选择:

  1. Using FormData:
    • Call its constructor passing the <form>element as an argument, and it will do all the work for you.
    • OR: create the object and then use the .append()method.
  2. Use a regular object and send it.
  3. Use a regular object, convert it to JSON and send it using contentType: 'application/json'.
  1. 使用FormData
    • 调用它的构造函数,将<form>元素作为参数传递,它会为你做所有的工作。
    • 或:创建对象,然后使用该.append()方法。
  2. 使用常规对象并发送它。
  3. 使用常规对象,将其转换为 JSON 并使用contentType: 'application/json'.

What option would you choose?It only depends on the back-end. If you are developing the back-end make sure you are retrieving the data from the POSTrequest in the correct way, otherwise check the site and see what kind of data you'll need to send.

你会选择什么选项?它只取决于后端。如果您正在开发后端,请确保POST以正确的方式从请求中检索数据,否则请检查站点并查看需要发送的数据类型。

Option 1

选项1

Create the FormDataobject:

创建FormData对象:

  • Method 1, let the constructor work for you:

    var form = document.getElementById("PhotoUploadForm"),
        myData = new FormData(form);
    
  • Method 2, do it by yourself:

    var fileData = this.files[0],
        myData = new FormData();
    
    myData.append('image', fileData);
    
  • 方法一,让构造函数为你工作:

    var form = document.getElementById("PhotoUploadForm"),
        myData = new FormData(form);
    
  • 方法二,自己动手:

    var fileData = this.files[0],
        myData = new FormData();
    
    myData.append('image', fileData);
    

Then, later in your code, you can send it:

然后,稍后在您的代码中,您可以发送它:

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    data: myData, // here it is
    ...
});

Option 2

选项 2

Create a regular object and send it:

创建一个常规对象并发送它:

var myData = {
        image: this.files[0]
    };

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    data: myData, // here it is
    ...
});

Option 3

选项 3

var myData = {
        image: this.files[0]
    };

myData = JSON.stringify(myData); // convert to JSON

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    contentType: 'application/json',
    data: myData, // here it is
    ...
});