How to send uploaded excel files from javascript t

2019-08-14 16:45发布

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>

This was what I have done so far.

1条回答
唯我独甜
2楼-- · 2019-08-14 17:01

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"];
查看更多
登录 后发表回答