使用flow.js + ng-flow将文件上载到WebAPI 2

Naf*_*tis 8 javascript angularjs typescript asp.net-web-api2 flow-js

我试图通过它的Angular包装器使用flow.js(https://github.com/flowjs/flow.js)(https://github.com/flowjs/ng-flow/tree/master/samples/basic)将文件上载到ASP.NET WebAPI 2服务器.无论如何,当我选择一个文件来上传我的WebAPI时,只获得第一个块GET请求,然后没有任何反应:没有POST完成,似乎flow.js没有启动上传.

选择文件时触发的初始GET是:

GET http://localhost:49330/api/upload?flowChunkNumber=1&flowChunkSize=1048576&flowCurrentChunkSize=4751&flowTotalSize=4751&flowIdentifier=4751-ElmahMySqlsql&flowFilename=Elmah.MySql.sql&flowRelativePath=Elmah.MySql.sql&flowTotalChunks=1 HTTP/1.1
Host: localhost:49330
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
Accept: */*
Referer: http://localhost:49330/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6
Run Code Online (Sandbox Code Playgroud)

响应是:

HTTP/1.1 202 Accepted
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcNDViXFRlc3RcVXBUZXN0XFVwVGVzdFxhcGlcdXBsb2Fk?=
X-Powered-By: ASP.NET
Date: Fri, 17 Apr 2015 08:02:56 GMT
Content-Length: 0
Run Code Online (Sandbox Code Playgroud)

然后,不再发出请求.

由于似乎没有最新的WebAPI示例,但只有零散的帖子,我为像我这样的新手创建了一个虚拟的repro解决方案,可以从http://1drv.ms/1CSF5jq下载:它是一个ASP.NET WebAPI 2在添加相应的API控制器后,我将上传代码放在主视图中的解决方案.只需按F5并尝试上传文件即可.您可以在中找到API控制器UploadController.cs.

相关的代码部分是:

a)客户端:类似于ng-flow页面的快速启动示例的页面:

<div class="row">
    <div class="col-md-12">
        <div flow-init="{target: '/api/upload'}"
             flow-files-submitted="$flow.upload()"
             flow-file-success="$file.msg = $message">
            <input type="file" flow-btn />
            <ol>
                <li ng-repeat="file in $flow.files">{{file.name}}: {{file.msg}}</li>
            </ol>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

相应的代码本质上是一个空的TS骨架,模块初始化:

module Up {
    export interface IMainScope {
    }

    export class MainController {
        public static $inject = ["$scope"];
        constructor(private $scope: IMainScope) {
        }
    }

    var app = angular.module("app", ["flow"]);
    app.controller("mainController", MainController);
}
Run Code Online (Sandbox Code Playgroud)

b)服务器端:我为所需脚本添加了一些补偿,以及从我在如何使用ng-Flow在ASP.NET中以块的形式上传文件中找到的示例代码修改了以下控制器.请注意,在GET Upload方法中,我使用绑定模型更改了签名(否则我们将获得404,因为路由未匹配),并且当找不到块时,我返回202 - Accepted代码而不是404,如flow.js文档所述200对应于"块已被接受且正确.无需重新上载",而404取消整个上载,而任何其他代码(如此处的202)告诉上传者重试.

[RoutePrefix("api")]
public class UploadController : ApiController
{
    private readonly string _sRoot;

    public UploadController()
    {
        _sRoot = HostingEnvironment.MapPath("~/App_Data/Uploads");
    }

    [Route("upload"), AcceptVerbs("GET")]
    public IHttpActionResult Upload([FromUri] UploadBindingModel model)
    {
        if (IsChunkHere(model.FlowChunkNumber, model.FlowIdentifier)) return Ok();
        return ResponseMessage(new HttpResponseMessage(HttpStatusCode.Accepted));
    }

    [Route("upload"), AcceptVerbs("POST")]
    public async Task<IHttpActionResult> Upload()
    {
        // ensure that the request contains multipart/form-data
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        if (!Directory.Exists(_sRoot)) Directory.CreateDirectory(_sRoot);
        MultipartFormDataStreamProvider provider = 
            new MultipartFormDataStreamProvider(_sRoot);
        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);
            int nChunkNumber = Convert.ToInt32(provider.FormData["flowChunkNumber"]);
            int nTotalChunks = Convert.ToInt32(provider.FormData["flowTotalChunks"]);
            string sIdentifier = provider.FormData["flowIdentifier"];
            string sFileName = provider.FormData["flowFilename"];

            // rename the generated file
            MultipartFileData chunk = provider.FileData[0]; // Only one file in multipart message
            RenameChunk(chunk, nChunkNumber, sIdentifier);

            // assemble chunks into single file if they're all here
            TryAssembleFile(sIdentifier, nTotalChunks, sFileName);

            return Ok();
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    private string GetChunkFileName(int chunkNumber, string identifier)
    {
        return Path.Combine(_sRoot,
            String.Format(CultureInfo.InvariantCulture, "{0}_{1}",
                identifier, chunkNumber));
    }

    private void RenameChunk(MultipartFileData chunk, int chunkNumber, string identifier)
    {
        string sGeneratedFileName = chunk.LocalFileName;
        string sChunkFileName = GetChunkFileName(chunkNumber, identifier);
        if (File.Exists(sChunkFileName)) File.Delete(sChunkFileName);
        File.Move(sGeneratedFileName, sChunkFileName);
    }

    private string GetFileName(string identifier)
    {
        return Path.Combine(_sRoot, identifier);
    }

    private bool IsChunkHere(int chunkNumber, string identifier)
    {
        string sFileName = GetChunkFileName(chunkNumber, identifier);
        return File.Exists(sFileName);
    }

    private bool AreAllChunksHere(string identifier, int totalChunks)
    {
        for (int nChunkNumber = 1; nChunkNumber <= totalChunks; nChunkNumber++)
            if (!IsChunkHere(nChunkNumber, identifier)) return false;
        return true;
    }

    private void TryAssembleFile(string identifier, int totalChunks, string filename)
    {
        if (!AreAllChunksHere(identifier, totalChunks)) return;

        // create a single file
        string sConsolidatedFileName = GetFileName(identifier);
        using (Stream destStream = File.Create(sConsolidatedFileName, 15000))
        {
            for (int nChunkNumber = 1; nChunkNumber <= totalChunks; nChunkNumber++)
            {
                string sChunkFileName = GetChunkFileName(nChunkNumber, identifier);
                using (Stream sourceStream = File.OpenRead(sChunkFileName))
                {
                    sourceStream.CopyTo(destStream);
                }
            } //efor
            destStream.Close();
        }

        // rename consolidated with original name of upload
        // strip to filename if directory is specified (avoid cross-directory attack)
        filename = Path.GetFileName(filename);
        Debug.Assert(filename != null);

        string sRealFileName = Path.Combine(_sRoot, filename);
        if (File.Exists(filename)) File.Delete(sRealFileName);
        File.Move(sConsolidatedFileName, sRealFileName);

        // delete chunk files
        for (int nChunkNumber = 1; nChunkNumber <= totalChunks; nChunkNumber++)
        {
            string sChunkFileName = GetChunkFileName(nChunkNumber, identifier);
            File.Delete(sChunkFileName);
        } //efor
    }
}
Run Code Online (Sandbox Code Playgroud)

Aid*_*das 5

200状态并不是唯一被认为成功的状态.201和202也是.阅读以下选项successStatuses:https: //github.com/flowjs/flow.js/blob/master/dist/flow.js#L91 因此,只需更改您需要的是返回204状态,这意味着No Content.

  • 谢谢,现在我的上传开始了!因此对于可能感兴趣的任何人,只需更改API控制器中GET方法的返回值即可返回ResponseMessage(new HttpResponseMessage(HttpStatusCode.NoContent)); (2认同)