2

我已经看到了许多使用 ng-flow 的示例,它们具有 php 端服务器来上传文件。但由于我不是 php 专家,我需要一些关于 webapi 的帮助,有人可以帮我找到一个工作示例或 ng-flow 教程和 webapi 文件上传。

谢谢大家。

4

1 回答 1

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);
    }
}
于 2015-03-16T07:44:18.197 回答