1

我有一个文件上传按钮,可以上传多个文件。我想使用 javascript 将这些文件存储到一个文件夹中,并将这些文件详细信息从视图发送到控制器。我正在做 mvc 4 razor 应用程序。我是 MVC 的新手。我知道它可以用 json 和 ajax post 方法来完成。但不知道如何使用这个。

 <script type="text/javascript">
       var fileNames = [];
       function handleFileUpload(evt) {
                     evt.stopPropagation();
                     evt.preventDefault();
                     var files = document.getElementById('file1').files;
                     for (var i = 0; files[i]; i++) {
                         fileNames.push(files[i]);
                     }
                  }
            $(function () {
                        $("#btnSubmit").click(function () {
                           $.post("@Url.Action("FileDetails")", { filename: JSON.stringify(fileNames) }, "json");
                      });
                 });
</script>

这就是我到目前为止所做的。

4

1 回答 1

2

I use a jquery plugin called Uploadify

HTML:

<input type="file" id="uploadBtn" />

Javascript:

<script type='javascript/text'>
$('#uploadBtn').uploadify({
        'uploader': '/uploadify/uploadify.swf',
        'script': 'URL',
        'cancelImg': '/uploadify/cancel.png',
        'buttonText': 'Upload',
        'auto': true,
        'multi': false,
        'removeCompleted': true,
        'simUploadLimit': 1,
        'scriptData': {  },
        'onAllComplete': function () {
           //finished
        }
    });
</script>

MVC ACTION:

public void UploadFile(){
 //Get the file
 HttpPostedFileBase upload = this.Request.Files[0];

 //DO STUFF
}

The url in the javascript method for the parameter 'script' will just be the url to your action. For example if the UploadFile action is in the controller Files then the url will be something like this:

/Files/UploadFile

You can also pass though extra data with 'scriptData' parameter and then just access them the following way

String name = Request["name"];
于 2013-07-08T06:04:43.260 回答