2012-09-12 94 views
3

我一直在爲客戶構建一個功能,使他們能夠從www.site1.com上載圖像,將圖像URL存儲到數據庫並將圖像存儲到www.site2.com/images上的文件中。我設法將文件上傳到目標位置,但是當我嘗試打開並查看圖像時,據說它包含錯誤。我從來沒有真的需要處理圖像,所以我不知所措。如何使用FtpWebRequest上傳圖片?

這是用來上傳文件的方法:

public static void UpLoadImage(Stream image, string target) 
    { 
     FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://www.site2.com/images/" + target); 
     req.UseBinary = true; 
     req.Method = WebRequestMethods.Ftp.UploadFile; 
     req.Credentials = new NetworkCredential("myUser", "myPass"); 
     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(); 
    } 

這是該方法是從所謂的(此搜索是一個HttpPostedFileBase):

myObject.UpLoadImage(image1.InputStream, storedTL.ID + "-1.png"); 

如果有辦法,我可以使這個代碼工作,或者如果有更好的方法來做到這一點,請幫助。

+0

您可以檢查是否上傳圖像成功創建 –

回答

9

StreamReader旨在讀取文本。

變化:

StreamReader rdr = new StreamReader(image); 
byte[] fileData = Encoding.UTF8.GetBytes(rdr.ReadToEnd()); 

byte[] fileData = File.ReadAllBytes(image); 
+0

非常感謝!那就是訣竅。 – Bazinga

+1

@JonEdwards很高興能幫到您 –

+0

現在我覺得有點笨。感謝你的回答。 –

0

老問題,但今天我損失了一些時間這個問題,並使用ReadAllBytes不是一種選擇我,讓我不得不只處理Streams。一些研究這裏後,我怎麼達到我的解決方案:

public void UploadToFTP(Stream stream, string ftpPath) 
    { 
     Stream requestStream = null; 

     try 
     { 

      Uri uri = GetServerUri(ftpPath); 

      FtpWebRequest request = Connect(uri); //here I set user/pwd/etc 
      request.UseBinary = true; 
      request.Method = WebRequestMethods.Ftp.UploadFile; 
      request.ContentLength = stream.Length; 

      requestStream = request.GetRequestStream(); 

      //Avoid to write zero length files in destiny. 
      //If you have read the stream before for any reason (as a convertion to Bitmap to extract dimensions, for example) 
      stream.Seek(0, SeekOrigin.Begin); 

      stream.CopyTo(requestStream); 

     } 
     catch (WebException ex) 
     { 
      //do something 
     } 
     finally 
     { 
      if (requestStream != null) 
       requestStream.Close(); 

     } 
    }