如何使用 AJAX 将文件上传到 ASP.NET? [英] How do I use AJAX to upload files to ASP.NET?

查看:34
本文介绍了如何使用 AJAX 将文件上传到 ASP.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AJAX 将文件上传到 ASP.NET.我有这个 Javascript:

I am trying to upload files using AJAX to ASP.NET. I have this Javascript:

var xhr = new XMLHttpRequest();

for (var i = 0; i < files.length; i++) {
   xhr.open('post', '/File/Upload', true);
   xhr.setRequestHeader("Content-Type", "multipart/form-data");
   var formData = new FormData();
   formData.append("_file", files[i]);
   xhr.send(files[i]);
}

files 是一个 Array()

然后我尝试在 C# 代码中访问 post 文件,但该值始终为 null.我该如何解决这个问题?

Then I try to access the post file in C# code, but the value is always null. How can I resolve this issue?

// Method 1, Result: file = null
HttpPostedFileBase file = Request.Files["_file"];

// Method 2, Result: postedFile.Count = 0
HttpFileCollectionBase postedFile = Request.Files;

推荐答案

假设您有以下包含文件输入字段的表单:

Assuming you have the following form containing the file input field:

<form action="/home/index" method="post" enctype="multipart/form-data" onsubmit="return handleSubmit(this);">
    <input type="file" id="_file" name="_file" multiple="multiple" />
    <button type="submit">OK</button>
</form>

您可以尝试以下功能:

function handleSubmit(form) {
    if (!FormData) {
        alert('Sorry, your browser doesn\'t support the File API => falling back to normal form submit');
        return true;
    }

    var fd = new FormData();
    var file = document.getElementById('_file');
    for (var i = 0; i < file.files.length; i++) {
        fd.append('_file', file.files[i]);
    }

    var xhr = new XMLHttpRequest();
    xhr.open(form.method, form.action, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    };
    xhr.send(fd);

    return false;
}

现在在服务器上,您应该能够使用 Request.Files 检索文件.

Now on the server you should be able to retrieve the file using Request.Files.

这篇关于如何使用 AJAX 将文件上传到 ASP.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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