在web api中上传ng-flow文件

时间:2015-03-16 06:39:57

标签: angularjs file-upload ng-flow

我见过很多ng-flow有php端服务器上传文件的例子。但由于我不是php的专家,我需要webapi的一些帮助,有人可以帮我找到一个有关webapi文件上传的ng-flow的工作示例或教程。

谢谢大家。

1 个答案:

答案 0 :(得分:0)

下面是我执行此操作的web-api代码

[HttpPost]
        public async Task<HttpResponseMessage> SaveFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
                Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);

            var provider = FileSaver.GetMultipartProvider();

            var result = await Request.Content.ReadAsMultipartAsync(provider);
            var fileInfo = FileSaver.MoveToTemp(result);
            return Request.CreateResponse(HttpStatusCode.OK, fileInfo);
        }

它使用自定义FileSaver

public class FileSaver
{
    public static MultipartFormDataStreamProvider GetMultipartProvider()
    {
        var uploadFolder = //your upload path;
        return new MultipartFormDataStreamProvider(uploadFolder);
    }

    private static string GetDeserializedFileName(MultipartFileData fileData)
    {
        var fileName = GetFileName(fileData);
        return JsonConvert.DeserializeObject(fileName).ToString();
    }

    private static string GetFileName(MultipartFileData fileData)
    {
        return fileData.Headers.ContentDisposition.FileName;
    }

    public static FileInfo MoveToTemp(MultipartFormDataStreamProvider result)
    {
        var originalFileName = GetDeserializedFileName(result.FileData.First());
        var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
        string timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
        var folder = Directory.CreateDirectory(**); //your upload path
        if (!folder.Exists) folder.Create();
        var filename = folder.FullName + @"\" + originalFileName;
        MoveFile(uploadedFileInfo, filename);
        return uploadedFileInfo;
    }

    private static void MoveFile(FileInfo fileInfo, string filename)
    {
        var count = 0;
        do
        {
            try
            {
                fileInfo.MoveTo(filename);
                return;
            }
            catch (Exception)
            {
                if (count == 4)
                {
                    throw;
                }
                count++;
                Thread.Sleep(1 * 1000);
            }
        } while (true);
    }
}