使用guid和文件扩展名上传ASP.NET WebApi文件

时间:2013-05-28 20:22:29

标签: file-upload asp.net-web-api

我目前能够保存正在上传到WebAPI控制器的文件,但我希望能够将文件保存为具有正确文件扩展名的guid,以便正确查看。

代码:

 [ValidationFilter]
    public HttpResponseMessage UploadFile([FromUri]string AdditionalInformation)
    {
        var task = this.Request.Content.ReadAsStreamAsync();
        task.Wait();

        using (var requestStream = task.Result)
        {
            try
            {
                // how can I get the file extension of the content and append this to the file path below?

                using (var fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + Guid.NewGuid().ToString())))
                {
                    requestStream.CopyTo(fileStream);
                }
            }
            catch (IOException)
            {                    
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }

        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.Created;
        return response;
    }

我似乎无法处理内容的实际文件名。我认为 headers.ContentDisposition.FileName 可能是一个候选人,但似乎没有填充。

1 个答案:

答案 0 :(得分:19)

感谢上面的评论,我指出了正确的方向。

为了澄清最终的解决方案,我使用了一个自动流式传输文件的MultipartFormDataStreamProvider。代码是我在这里发布的另一个问题: MultipartFormDataStreamProvider and preserving current HttpContext

我的完整提供商代码如下所示。生成guid文件名的关键是覆盖GetLocalFileName函数并使用headers.ContentDisposition属性。提供者处理内容到文件的流式传输。

public class MyFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public MyFormDataStreamProvider (string path)
        : base(path)
    { }

    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
    {
        // restrict what images can be selected
        var extensions = new[] { "png", "gif", "jpg" };
        var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty);

        if (filename.IndexOf('.') < 0)
            return Stream.Null;

        var extension = filename.Split('.').Last();

        return extensions.Any(i => i.Equals(extension, StringComparison.InvariantCultureIgnoreCase))
                   ? base.GetStream(parent, headers)
                   : Stream.Null;

    }

    public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
    {
        // override the filename which is stored by the provider (by default is bodypart_x)
        string oldfileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
        string newFileName = Guid.NewGuid().ToString() + Path.GetExtension(oldfileName);

        return newFileName;       
    }
}