2015-08-31 63 views
1

我想通過ASP.Net中的FTP上傳圖像文件。圖像文件上傳到正確的位置,但是當我讀取或下載它時,它已損壞。我的代碼如下:ASP.Net FTP上傳不起作用

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); 
    } 
} 

我是否錯過了什麼?該文件上傳完美,但由於某種原因它被損壞。

回答

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 
} 
+0

問題仍然存在 –

+0

@FahadAmin向我們顯示您的更新代碼,以便我們檢查您是否正確應用了Ondrej的建議。 –

+0

只需在原始文章中編輯代碼。 CopyStream()方法與Ondrej建議的完全相同 –