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



我目前能够保存正在上传到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可能是一个候选,但似乎没有得到填充。

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

为了澄清最终的解决方案,我使用了MultipartFormDataStreamProvider,它自动流式传输文件。代码是在另一个问题,我张贴到一个不同的问题在这里:MultipartFormDataStreamProvider并保留当前的HttpContext

完整的提供程序代码列在下面。生成guid文件名的关键是覆盖GetLocalFileName函数并使用头文件。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;       
    }
}

最新更新