【问题标题】:Files uploaded to ftp server, corrupted why? [duplicate]文件上传到 ftp 服务器,为什么会损坏? [复制]
【发布时间】:2022-01-02 00:27:56
【问题描述】:

文件已成功上传,但文件已损坏。 请检查我的代码并解决我的问题。 我认为我的问题在这一行:

 byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());;
string ftpurl = "ftp://IP";
            string ftpusername = "u09z0fyuu"; // e.g. username
            string ftppassword = "Yamankatita1@"; // e.g. password

            string PureFileName = new FileInfo(file_name).Name;
            String uploadUrl = String.Format("{0}/{1}/{2}", ftpurl, "PDPix", file_name);
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // This example assumes the FTP site uses anonymous logon.  
            request.Credentials = new NetworkCredential(ftpusername, ftppassword);
            request.Proxy = null;
            request.KeepAlive = true;
            request.UseBinary = true;
            request.UsePassive = true;
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // Copy the contents of the file to the request stream.  
            StreamReader sourceStream = new StreamReader(_mediaFile.Path);
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());;
            sourceStream.Close();
            request.ContentLength = fileContents.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            _ = DisplayAlert("Upload File Complete, status {0}", response.StatusDescription,"OK");

【问题讨论】:

  • 您上传的是 UTF8 编码的文本文件吗?如果不是,那似乎是您的问题。
  • 不,我只需要上传图片文件。请帮助我,谢谢!

标签: c# server ftp upload


【解决方案1】:

您说过您正在尝试上传图像文件。您不能将它们视为 UTF8,因为它们是二进制数据,并且它们不是用 UTF8 编码的。您需要将二进制数据视为二进制数据。

你可以直接读取字节:

byte[] fileContents = File.ReadAllBytes(_mediaFile.Path);

说明

UTF8 无法将 byte (0x00 - 0xFF) 的所有可能值表示为字符并将它们再次往返返回为二进制格式。我们可以通过以下代码观察到这一点:

byte[] input = new byte[8];
RNGCryptoServiceProvider.Create().GetBytes(input);

Console.WriteLine(string.Join(", ", input.Select(i => i)));

string tmp = System.Text.Encoding.UTF8.GetString(input); // interpret arbitrary bianry data as text
// the data is corrupted by this point
byte[] result = System.Text.Encoding.UTF8.GetBytes(tmp); // convert the text back to a binary form (utf8-encoded)
Console.WriteLine(string.Join(", ", result.Select(i => i)));

Try it online

这里我们生成 8 个随机字节,打印它们的值,尝试将它们解释为 string,将该字符串转换回字节,然后打印它们的新值。

对于以下 8 个字节:

16, 211, 7, 253, 207, 91, 24, 137

我们得到以下字节:

16, 239, 191, 189, 7, 239, 191, 189, 239, 191, 189, 91, 24, 239, 191, 189

就这样,我们的数据被破坏了!长话短说:不要对二进制数据使用文本编码。

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多