【问题标题】:WebClient UploadFile and Storing on the serverWebClient UploadFile 并存储在服务器上
【发布时间】:2019-08-02 13:53:13
【问题描述】:

我有一个小型控制台应用程序,它将文件上传到我的网络服务,两者都在我的 Windows 10 机器上本地运行。

将文件上传到 Web 服务的控制台应用代码:

using (var client = new WebClient())
{
    client.UploadProgressChanged += ...;
    client.UploadFileCompleted += ...;
    await client.UploadFileTaskAsync(wsURL, "POST", FilePath);
}

然后是网络服务代码,将流复制到一个新文件中:

[OperationContract]
[WebInvoke(Method = "POST")]
public bool Upload(Stream fs)
{
    using (var file = File.Open(NewFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
    {
        fs.CopyTo(file);
    }

    return true;
}

看起来文件上传正常,并且在网络服务上存储得非常好,没有问题。

当我浏览到上传的副本(此时基本上复制到我机器上的另一个位置)并尝试打开文件时,它不会打开。当我将原始文件的元数据与上传的文件进行比较时,元数据在新文件中全部消失了。

  • EXE 不会再打开了。
  • JPG 无法使用 Windows 照片查看器或画图打开。仅在 Photoshop 中。
  • PNG 似乎完全没有问题。

我错过了什么?我尝试先将文件流读入MemoryStream,然后再读入文件,仍然以正确的大小/内容长度保存文件,但没有元数据:

【问题讨论】:

    标签: c# upload metadata webclient


    【解决方案1】:

    您正在尝试存储包含边界字节的文件流。

    在这里查看WebClient UploadFileAsync的源码: https://referencesource.microsoft.com/#system/net/System/Net/webclient.cs2389线

    尝试以下操作,干净地上传文件:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
    request.ServicePoint.Expect100Continue = false;
    request.Method = "POST";
    request.ContentType = MimeMapping.GetMimeMapping(FilePath);
    
    using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    using(Stream requestStream = request.GetRequestStream())
    {
        byte[] buffer = new byte[1024 * 4];
        int bytesLeft = 0;
        while((bytesLeft = fs.Read(buffer, 0, buffer.Length)) > 0)
        {
            requestStream.Write(buffer, 0, bytesLeft);
        }
    }
    
    using (var response = (HttpWebResponse)request.GetResponse())
    using (var responseStream = response.GetResponseStream())
    using (var sr = new StreamReader(responseStream))
    {
        var responseString = sr.ReadToEnd();
    }
    

    【讨论】:

    • 你拯救了我的一天。没有注意到它在流中添加了额外的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2015-03-02
    • 2014-10-15
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多