如何从JavaScript中获取FormData中的数据?

时间:2013-02-14 14:19:19

标签: javascript qunit form-data

我需要从FormData读取数据吗?我尝试阅读类似someFormatData["valueName"]的内容,但它不起作用。 options["fileId"]options["file"]不起作用。我也尝试options.fileId相同的结果:

function upload(file, fileId, callback) {
    var formData = new FormData();
    formData.append("file", file);
    formData.append("fileID", fileId);

    $.ajax({
        url: '/url',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            callback(response);
        }
    });
}


asyncTest("test upload chunk", function() {
    var blob = new Blob(["Hello world!"], { type: "text/plain" }),        
        options = null,
        fileID ="someFileID",
        response;

    jQuery.ajax = function(param) {
        options = param;   // THIS is FormData object 
        // how to read fileId and file from here
    };

    upload(blob, fileID, function (data) {
        response = data;  
    });

    options.success({
        someProp: 'responseFromServer'
    });

    setTimeout(function() {
        QUnit.equal(options, "dataTosend", "parameters is OK");
        QUnit.equal(response["someProp"], "responseFromServer", "Response ok");
        start();
    },1000);
});

1 个答案:

答案 0 :(得分:2)

如果您使用FormData对象,可以使用几种不同的方法...您要找的是

protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpPostedFile filePosted = Request.Files["newinput"];
        string base64String = filePosted.ToString();

            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);

//I DONT KNOW HOW TO WRITE ABOVE INTO THE SaveAs CONDITION BELOW


        if (filePosted != null && filePosted.ContentLength > 0)
        {
            string fileNameApplication = Path.GetFileName(filePosted.FileName);
            string fileExtensionApplication = Path.GetExtension(fileNameApplication);

            // generating a random guid for a new file at server for the uploaded file
            string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
            // getting a valid server path to save
            string filePath = Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile);

            if (fileNameApplication != String.Empty)
            {
                filePosted.SaveAs(filePath);
            }

        }

formData.get()

https://developer.mozilla.org/en-US/docs/Web/API/FormData

请注意,并非所有浏览器都完全支持get()方法。