Javascript / jQuery追加到FormData()返回'undefined' [英] Javascript/jQuery Append to FormData() returns 'undefined'

查看:322
本文介绍了Javascript / jQuery追加到FormData()返回'undefined'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

   $('#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");
            }
        });
    });

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

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'

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

当我在console.log(data)时得到以下内容:

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

FormData {append: function}__proto__: FormData

我在这里做错了吗?为什么 data.image & data.content undefined?当我输出 this.files [0] 时,我得到以下内容:

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

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?

推荐答案

问题



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

Issue

You are misunderstanding the FormData object. A FormData object has only an .append() method, which doesn't append properties to it, but only stores the data provided. Hence, obviously, the .image and .content properties will be undefined.

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

If you want to create a object with the .image and .content properties you should instead create a regular object and then send it.

到实现你想要的你有一些选择:

To achieve what you want you have some options:


  1. 使用 FormData

    • 调用其构造函数传递< form> 元素作为参数,它将为您完成所有工作。

    • 或者:创建对象,然后使用 .append()方法。

  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.

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

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 POST request in the correct way, otherwise check the site and see what kind of data you'll need to send.

创建 FormData 对象:


  • 方法1,让构造函数为你工作:

  • Method 1, let the constructor work for you:

var form = document.getElementById("PhotoUploadForm"),
    myData = new FormData(form);


  • 方法2,自己动手:

  • Method 2, do it by yourself:

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



    选项2



    创建常规对象并发送:

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



    选项3



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

    这篇关于Javascript / jQuery追加到FormData()返回'undefined'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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