让上传者和上传

问题描述:

我使用了一个简单的代码上传文件到我的网站,这里是我的代码:让上传者和上传

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#代码将文件上传到我的网站?

谢谢。

要上传文件,您需要使用“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); 
    } 
}