【问题标题】:Save MultipartFileData file to disk将 MultipartFileData 文件保存到磁盘
【发布时间】:2013-12-19 09:42:44
【问题描述】:

我有在其他线程中看到的波纹管代码,但它实际上并没有显示如何将 MultipartFileData 文件保存到磁盘。

[HttpPost]
public Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath(Settings.AssetImageTempStorage);
    var provider = new MultipartFormDataStreamProvider(root);

    // Read the form data and return an async task.
    var task = Request.Content.ReadAsMultipartAsync(provider).
        ContinueWith<HttpResponseMessage>(t =>
        {
            if (t.IsFaulted || t.IsCanceled)
            {
                Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
            }

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                // HOW DO I SAVE THIS FILE TO DISK HERE ???
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        });

    return task;
}

【问题讨论】:

  • 你看this的问题了吗?有一行File.Copy(fileData.LocalFileName, Path.Combine(StoragePath, fileName));,我认为它将收到的文件复制到特定位置。
  • 感谢 mozgow,我让它以类似的方式工作。现在工作正常,但在 IE8 和 IE9 中我得到响应:HTTP/1.1 415 Unsupported Media Type。在 IE10 中很好但低于我得到这个愚蠢的错误,完全不知道为什么。
  • 抱歉,发现问题了。我使用的是 blueimp blueimp.github.io/jQuery-File-Upload/basic.html 文件上传器。它附带了一个用于旧版浏览器的 iframe JS 文件,我没有包括在内。我现在已经包含了它,它工作正常。
  • user2520440 早已不复存在,但代码中的问题..“我如何将这个文件保存到磁盘上???”有一个简单的答案:你不需要。它已经保存在 .ReadAsMultipartAsync() 中,这是触发保存的原因。

标签: c#-4.0 multipart multifile-uploader


【解决方案1】:

这是在服务器中保存文件的示例。希望这会对你有所帮助。

public class TestController : ApiController
{
    const string StoragePath = @"T:\WebApiTest";
    public async Task<HttpResponseMessage> Post()
    {
        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));
            await Request.Content.ReadAsMultipartAsync(streamProvider);
            foreach (MultipartFileData fileData in streamProvider.FileData)
            {
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
                }
                string fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName));
            }
        }
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
    }
}

【讨论】:

  • 我遇到了File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName)); 偶尔出现“文件正在使用”异常的问题。
  • @enorl76 抱歉回复晚了。我认为不应该有“文件正在使用”的例外。但是,如果您遇到此异常,您可以尝试 File.Copy() 而不是 File.Move()。因为,即使源文件正在被另一个进程使用,方法 File.Copy() 也会被执行。 System.IO.File.Copy(@"E:\asd.txt", @"F:\asd_copy.txt", true);
  • 在哪里可以找到如何在客户端(.NET)中上传数据?
  • @Shimmy 抱歉,我没听懂你的问题?
  • @Shimmy 哦,对不起。我无法回答这个问题,因为我没有尝试任何其他类型。如果您可以进行实验并与我们分享您的宝贵结论,这将对所有人都非常有帮助。
猜你喜欢
  • 2016-07-22
  • 2010-09-23
  • 2010-11-08
  • 2021-11-03
  • 2019-10-30
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多