2013-04-03 31 views
1

我有一個C#.net Web應用程序可以發送(通過POST方法)文件到另一個應用程序。在第二個應用程序中,我有以下代碼來檢索發佈的文件。處理HttpPostedFile在C#

HttpPostedFile hpf = Request.Files[0]; 

現在我可以通過代碼的文件保存

hpf.SaveAs("The path to be saved"); 

我需要再次發送到另一個應用程序,而不在這裏保存它(沒有第二個申請保存我需要把它到第三個應用程序)。

(現在我能做的就是將文件保存在第二個應用程序,並從那裏通過給定路徑完全相同正如我在我的第一個應用程序沒有將其發佈到第三個應用程序。但是,我需要另一種解決方案。)

我試過hpf.fileName,但它只給出文件名(例如:test.txt)。當我像下面一樣嘗試時

string file = hpf.FileName; 
string url = "the url to send file"; 
    using (var client = new WebClient()) 
    { 
     byte[] result = client.UploadFile(url, file); 
     string responseAsString = Encoding.Default.GetString(result); 
    } 

WebException發生像'WebClient請求期間發生異常'。

是否有任何方法在C#.net中執行它?

+0

您可以將文件轉換爲byte []並將服務修改爲接受字節。 – Ratna

+0

如何將hpf轉換爲byte []並將服務修改爲接受字節 – Sudha

回答

2

創建字節數組 How to create byte array from HttpPostedFile

這裏是爲了節省字節的Web服務的方法

[WebMethod] 
public string UploadFile(byte[] f, string fileName, string bcode) 
{ 
    if (bcode.Length > 0) 
    { 
     try 
     { 
      string[] fullname = fileName.Split('.'); 
      string ext = fullname[1]; 
      if (ext.ToLower() == "jpg") 
      { 
       MemoryStream ms = new MemoryStream(f); 
       FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath("~/bookimages/zip/") + bcode+"."+ext, FileMode.Create); 
       ms.WriteTo(fs); 
       ms.Close(); 
       fs.Close(); 
       fs.Dispose(); 


      } 
      else 
      { 
       return "Invalid File Extention."; 
      } 
     } 
     catch (Exception ex) 
     { 
      return ex.Message.ToString(); 
     } 
    } 
    else 
    { 
     return "Invalid Bookcode"; 
    } 

    return "Success"; 
} 
+0

在這裏可以byte [] f和string bcode是什麼? – Sudha

+0

抱歉,您可以忽略bcode,因爲我將它從我的庫中粘貼。 byte [] f是將hpf轉換爲byte []時將得到的byte []。 – Ratna

+0

好的拉特納..我知道了 – Sudha

2

事情是,如果你不希望使用Web服務作爲在前面的回答表明,你需要使用你的HttpPostedFile的InputStream屬性。您應該使用HttpWebRequest對象來創建請求與您的文件內容。有很多帖子和教程,包括thisthis

+0

我只有這個HttpPostedFile hpf = Request.Files [0];在我的第二次申請。如果不在第二個應用程序中保存文件,我如何將它發佈到第三個應用程序中? – Sudha

+0

您應該閱讀我答案中鏈接的文章。這正是你需要的。特別是第二個 - [這](http://stackoverflow.com/questions/11048258/uploadfile-with-post-values-by-webclient) – brke