我正在尝试通过FTP在ASP.Net上传图像文件。图像文件上传到正确的位置,但是当我阅读或下载图像文件时,它已损坏。我的代码如下:
protected void FTPUpload()
{
//FTP Server URL.
string ftp = ConfigurationManager.AppSettings.Get("FTPServer");
//FTP Folder name.
string ftpFolder = "images/logos/";
//FTP Credentials
string ftpUsername = ConfigurationManager.AppSettings.Get("FTPUsername");
string ftpPassword = ConfigurationManager.AppSettings.Get("FTPPassword");
byte[] fileBytes = null;
//Read the FileName and convert it to Byte array.
string fileName = Path.GetFileName(fuLogo.FileName);
using (StreamReader fileStream = new StreamReader(fuLogo.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
try
{
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
//Enter FTP Server credentials.
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (var requestStream = request.GetRequestStream())
{
CopyStream(fuLogo.PostedFile.InputStream, requestStream);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//lblMessage.Text += fileName + " uploaded.<br />";
response.Close();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
}
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[1024000];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
我错过了什么吗?该文件已完美上传,但由于某种原因,它已损坏。
答案 0 :(得分:1)
这部分气味:
using (StreamReader fileStream = new StreamReader(fuLogo.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
没有理由首先将图像复制到数组(并在此期间使用默认文本编码/ UTF8解码) - 只需执行流到流的复制(参见How do I copy the contents of one stream to another? )功能:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
所以ftp上传应该只是
using (var requestStream = request.GetRequestStream())
{
CopyStream(fuLogo.PostedFile.InputStream, requestStream);
// no need to requestStream.Close(); - using does that for you
}