我试图在ASP.NET中使用FTP模式上传PDF文件,文件上传成功但结果文件已损坏,请给我解决方案。
public void UploadFTPTextFile(string ftpServer, string ftpFolder, string user, string passward, string NName, FileUpload FileUpload1)
{
byte[] fileBytes = null;
string fileName = NName;
using (StreamReader fileStream = new StreamReader(FileUpload1.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(user, passward);
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Close();
}
}
答案 0 :(得分:1)
我认为问题是将输入文件读取为字节。您认为它是UTF8编码,但FTP不解释文本,不需要编码。你应该只读取字节,因为FTP服务器只保存字节。请改用File.ReadAllBytes。
public void UploadFTPTextFile(string ftpServer, string ftpFolder, string user, string passward, string NName, FileUpload FileUpload1)
{
string fileName = NName;
byte[] fileBytes = File.ReadAllBytes(fileName);
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(user, passward);
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Close();
}
}
如果您想使用更优雅的解决方案(对于大文件),请使用Stream.CopyTo并将打开的文件复制到requestStream而不使用fileBytes。