2012-05-03 40 views
0

如何將流數據保存爲ftp服務器中的圖像?如何在c#中的FTP服務器保存圖像?

FileInfo fileInf = new FileInfo("1" + ".jpg"); 
         string uri = "ftp://" + "hostip//Data//" + fileInf.Name; 
         FtpWebRequest reqFTP; 

         // Create FtpWebRequest object from the Uri provided 
         reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(
          "ftp://" + "ipaddress//Data//" + fileInf.Name)); 

         // Provide the WebPermission Credintials 
         reqFTP.Credentials = new NetworkCredential("username", 
                   "password"); 

         // By default KeepAlive is true, where the control connection is 
         // not closed after a command is executed. 
         reqFTP.KeepAlive = false; 

         // Specify the command to be executed. 
         reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 

         // Specify the data transfer type. 
         reqFTP.UseBinary = true; 

         // Notify the server about the size of the uploaded file 
         //reqFTP.ContentLength = fileInf.Length; ??? 
         using (var img = Image.FromStream(image)) 
         { 
          img.Save(adduser.User_Id + ".jpg", ImageFormat.Jpeg); 
         } 

你能告訴我嗎?

+1

爲下載文件的示例代碼請告訴我問題嗎? – Likurg

回答

1

您需要將數據(圖像)轉換爲字節數組然後發送。 FtpWebRequest.GetResponse documentation示例顯示了基本信息,儘管它附加了一個文件。其他一切都與你正在做的事情有關(你會用上傳文件替換附件)。

以獲取圖像到一個字節數組,你可以這樣寫:

byte[] imageBuffer = File.ReadAllBytes(imageFileName); 

其他的一切應該是非常相似的文檔的例子。

0

下面是從FTP服務器

Uri url = new Uri("ftp://ftp.demo.com/Image1.jpg"); 
if (url.Scheme == Uri.UriSchemeFtp) 
{ 
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url); 
    //Set credentials if required else comment this Credential code 
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword"); 
    objRequest.Credentials = objCredential; 
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile; 
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse(); 
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream()); 
    byte[] buffer = new byte[16 * 1024]; 
    int len = 0; 
    FileStream objFS = new FileStream(Server.MapPath("Image1.jpg"), FileMode.Create, FileAccess.Write, FileShare.Read); 
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0) 
    { 
     objFS.Write(buffer, 0, len); 
    } 
    objFS.Close(); 
    objResponse.Close(); 
}