如何从JavaScript发送上传Excel文件到控制器的MVC 4控制器、上传、文件、JavaScript

2023-09-10 20:45:15 作者:西红柿小生

我有一个文件上传按钮,可以上传多个文件。我想使用javascript上存储这些文件的文件夹,并从视图控制器发送这些文件​​的详细信息。我做的MVC 4剃须刀的应用程序。是新来的MVC。我知道,它可以使用JSON和Ajax后方法进行。但不知道如何使用这个。

I have a file upload button which can upload multiple files. I want to store these files on to a folder using javascript and send these file details from view to the controller. I am doing mvc 4 razor app. Am new to MVC. I know that it can be done with json and ajax post methods. But dont know how to use this.

 <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>

这是我迄今所做的。

推荐答案

我用一个jQuery插件叫做 Uploadify

I use a jquery plugin called Uploadify

HTML:

&LT;输入类型=文件ID =uploadBtn/&GT;

JavaScript的:

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行动:

MVC ACTION:

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

 //DO STUFF
}

在为参数脚本的JavaScript方法的URL将只是链接到你的行动。例如,如果UploadFile动作控制器文件,那么该URL会是这样的:

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:

/文件/ UploadFile

/Files/UploadFile

您还可以通过使用虽然scriptData'参数额外的数据,然后只需访问它们以下列方式

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

String name = Request["name"];