我目前能够保存正在上传到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函数并使用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; } }