2017-04-08 29 views
1

我使用了一個簡單的代碼上傳文件到我的網站,這裏是我的代碼:讓上傳者和上傳

protected void UploadFile(object sender, EventArgs e) 
{ 
    string folderPath = Server.MapPath("~/Files/"); 

    if (!Directory.Exists(folderPath)) 
     Directory.CreateDirectory(folderPath); 

    FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName)); 

    lblMessage.Text = Path.GetFileName(FileUpload1.FileName) + " has been uploaded.<br/>" 
     +"<br/>bytes: " + FileUpload1.FileBytes.Length 
     + "<br/>Streams: "+ FileUpload1.FileContent.Length 
     + "<br/>fName: " + FileUpload1.FileName; 
} 

FileUpload1是System.Web.UI.WebControls.FileUpload。 如何通過C#代碼將文件上傳到我的網站?

謝謝。

回答

1

要上傳文件,您需要使用「multipart/form-data」類型的POST請求。 示例代碼:

//create http client 
using (var client = new HttpClient()) 
{ 
    //create the content we need 
    using (var multipartFormDataContent = new MultipartFormDataContent()) 
    { 
     //read the file as bytes 
     var bytes = //file content 

     //wrap it into the formdata 
     multipartFormDataContent.Add(new ByteArrayContent(bytes)); 

     //do the post request and retrieve the response from the server 
     var result = await client.PostAsync("myUrl.com", multipartFormDataContent); 
    } 
}