我使用此代码将图像上传到 ftp。但图像已损坏。
我尝试上传的图像是 Base64
字符串。我将其转换为流并将其传递给 UpLoadImage。
public static void UpLoadImage(Stream image, string target)
{
FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://www.examp.com/images/" + target);
req.UseBinary = true;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential("UserNm", "PassWd");
StreamReader rdr = new StreamReader(image);
byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd());
rdr.Close();
req.ContentLength = fileData.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(fileData, 0, fileData.Length);
reqStream.Close();
}
代替:
StreamReader rdr = new StreamReader(image); byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd()); rdr.Close();
如果我使用 byte[] fileData = File.ReadAllBytes(image);
它给了我一个错误,文件名超过了 260 个字符。
请有人帮忙解决这个问题..
最佳答案
点赞评论说 使用
byte[] fileData = File.ReadAllBytes(filePath);
对于所有不是文本文件的文件。
像那样:
private void FTPUPLOAD(string imgPath)
{
FTPDelete(img);
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(BaseUrl +Path.GetFileName(imgPath));
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(Account, Password);
// Copy the contents of the file to the request stream.
//THIS IS THE CODE
byte[] fileContents = File.ReadAllBytes(imgPath);
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
关于c# - 使用 ftpwebrequest 上传到 ftp 时图像损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15826149/