制作上传器并上传

时间:2017-04-08 09:34:18

标签: c# asp.net uwp

我正在使用一个简单的代码将文件上传到我的网站,这是我的代码:

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 个答案:

答案 0 :(得分:1)

要上传文件,您需要使用类型为&#34; multipart / form-data&#34;的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);
    }
}