简体   繁体   English

Asp.net MVC异步上传问题

[英]Asp.net MVC Async upload Issue

We are working on a file upload and have chosen the blueimp plugin. 我们正在上载文件,并选择了blueimp插件。 We have this working in the following way. 我们通过以下方式进行工作。

User selects all files they wish to upload and clicks a button to upload all in one go. 用户选择他们希望上传的所有文件,然后单击一个按钮一次上传所有文件。

This part works fine and sends all files at once to the server. 这部分工作正常,并将所有文件一次发送到服务器。

The server code sample only is as follows. 仅服务器代码示例如下。

public async Task<ActionResult> Upload()
{
    var result = await new Uploader().UploadFile(Request.Files[0]);
    return Json(result);
}
public class Uploader
{
    public async Task<UploadResult> UploadFile(HttpPostedFileBase file)
    {
        //do file processing and save file to disk
        var filerecord = _fileService.GetById(xxxx);
        filerecord.files.Add(new Info { name = file.FileName, size = file.ContentLength });
        //Here for us its Mongo but any not sure what the result would be against another db
        await _fileService.SaveAsync(filerecord);
        return new UploadResult { message = "ok" };
    }
}

//js
    fi.fileupload({
        url: 'uploadfile',
        dataType: 'json',
        autoUpload: false,
        singleFileUploads:false,
        maxNumberOfFiles: maxFiles,
        acceptFileTypes: /(\.|\/)(jpe?g)$/i,
        maxFileSize: 1048576*2, //1MB
        messages: { },
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: true,
        previewMaxWidth: 50,
        previewMaxHeight: 50,
        previewCrop: false,
        dropZone: $('#dropzone')
    });

    fi.on('fileuploadadd', function (e, data) {

        $('form').submit(function (e) {
            data.submit();
            return false;
        });
});

Just a note that the db in this case is Mongo 请注意,本例中的数据库是Mongo

The Problem Uploading single files at a time ie select a file click upload all works as expected. 一次上载单个文件的问题 ,即选择一个文件,然后单击“全部上载”。 Select more than one file and hit upload button all files are uploaded and saved to the disk without an issue. 选择多个文件,然后单击上载按钮,所有文件都将被上载并保存到磁盘,而不会出现问题。 However I would expect the following behaviour 但是我期望以下行为

  1. Get record from db 从数据库获取记录
  2. Add info about the file 添加有关文件的信息
  3. Save the record 保存记录

As mentioned this works great with one file at a time but when they all come in at once I am guessing the async behaviour causes the method to loose context of what file its working on as the 3 steps in the debugger seem to be called per file randomly rather than in order. 如前所述,这一次只能处理一个文件,但是当它们一次全部进入时,我猜测异步行为会导致该方法失去其正在处理的文件的上下文,因为调试器中的3个步骤似乎每个文件都被调用随机而不是顺序。

I have tried various approaches like change the order of the way things happen, also using ConfigureAwait etc. 我尝试了各种方法,例如更改事情发生的顺序,也使用ConfigureAwait等。

Any advice would be appreciated. 任何意见,将不胜感激。

If i understand your case correctly this code should work for you: 如果我正确理解您的情况,此代码应为您工作:

public async Task<ActionResult> Upload()
{
    var files = new HttpPostedFileBase[Request.Files.Count];
    Request.Files.CopyTo(files, 0);
    var tasks = files.Select(f=>new Uploader().UploadFile(f));
    await Task.WhenAll(tasks);
    return Json(tasks.Where(v=>v.Status == TaskStatus.RanToCompletion ).Select(v=>v.Result).ToList());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM