加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

使用asp.net mvc中的Ajax将文件和文本上传到服务器

发布时间:2020-12-16 09:55:41 所属栏目:asp.Net 来源:网络整理
导读:问候语. 我想使用ajax将图像与描述一起上传到服务器. fileupload工作正常,虽然我无法弄清楚如何提取输入的文本. 基本上表单看起来像这样: form id="uploader" input id="fileInput" type="file" multiple input type="text" id="fileText" name="fileText"
问候语.

我想使用ajax将图像与描述一起上传到服务器.

fileupload工作正常,虽然我无法弄清楚如何提取输入的文本.

基本上表单看起来像这样:

<form id="uploader">
     <input id="fileInput" type="file" multiple>
     <input type="text" id="fileText" name="fileText" value=" " />
     <input type="submit" value="Upload file" />
</form>

上传到服务器的脚本如下所示:

document.getElementById('uploader').onsubmit = function () {
        var formdata = new FormData(); //FormData object
        var fileInput = document.getElementById('fileInput');
        //Iterating through each files selected in fileInput
        for (i = 0; i < fileInput.files.length; i++) {
            //Appending each file to FormData object
            formdata.append(fileInput.files[i].name,fileInput.files[i]);
        }
        //Creating an XMLHttpRequest and sending
        var xhr = new XMLHttpRequest();
        xhr.open('POST','/Controller/Action');
        xhr.send(formdata);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert(xhr.responseText);
            }
        }
        return false;
    }

在服务器端,在相关操作的控制器中:

public JsonResult Upload(){
     for (int i = 0; i < 9; i++){
           HttpPostedFileBase file = Request.Files[i]; //Uploaded files
           //Do stuff with uploaded files
     }            
}

我尝试过的:

>更改了Upload方法以获取名为fileText的字符串参数.
>更改脚本以将文本附加到for循环中的这两行的formdata:

var fileText = document.getElementById(‘fileText’);

formdata.append(fileText.value,fileText.value)

我可能在两次试验中都遗漏了一些东西,但我似乎无法弄清楚是什么.请帮忙!

问候,
克里斯

解决方法

  1. Changed the Upload method to take in a string parameter named fileText.

正确.

  1. Changed the script to also appent the text to the formdata with these two lines inside the for-loop:

不正确.你不应该在循环中这样做,因为你只有一个文本输入字段,所以你只能发送1个值.所以将此代码移到循环之外.您还应在追加到FormData时指定正确的名称,该名称必须与您的控制器操作参数名称匹配:

var fileText = document.getElementById('fileText');
formdata.append('fileText',fileText.value);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读