隐藏

C# WebClient实现文件上传

发布:2022/6/17 8:40:04作者:管理员 来源:本站 浏览次数:1442

一、同步上传

文章 https://www.cnblogs.com/duanjt/p/6420172.html 里面有提到服务端通过WebApi如何实现文件上传,这里就只说客户端使用WebClient上传,直接上代码:

private void button2_Click(object sender, EventArgs e)
{

    try

    {

        string url = "http://localhost:29817/api/values/SaveFile";

        if (string.IsNullOrEmpty(this.textBox1.Text))

        {

            MessageBox.Show("请先选择要上传的文件");

            return;

        }

        string fileName = this.textBox1.Text;//文件全路径(e:\abc.txt)

        string safeFileName = Path.GetFileName(fileName);//文件名(abc.txt)

        WebClient client = new WebClient();

        client.Credentials = CredentialCache.DefaultCredentials;

        client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data

        client.QueryString["fname"] = safeFileName;

        byte[] fileb = client.UploadFile(new Uri(url), "POST", fileName);

        string res = Encoding.UTF8.GetString(fileb);

        MessageBox.Show(res);

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message);

    }

}

注意:

1.Header的Content-Type必须设置为application/form-data

二、异步上传

上面是同步方式上传,下面是异步方式上传

private void button2_Click(object sender, EventArgs e)

{

    try

    {

        string url = "http://localhost:29817/api/values/SaveFile";

        if (string.IsNullOrEmpty(this.textBox1.Text))

        {

            MessageBox.Show("请先选择要上传的文件");

            return;

        }

        string fileName = this.textBox1.Text;//文件全路径(e:\abc.txt)

        string safeFileName = Path.GetFileName(fileName);//文件名(abc.txt)

        WebClient client = new WebClient();

        //定义事件,上传成功事件和上传进度事件

        client.UploadFileCompleted += client_UploadFileCompleted;

        client.UploadProgressChanged += client_UploadProgressChanged;

        client.Credentials = CredentialCache.DefaultCredentials;

        client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data

        client.QueryString["fname"] = safeFileName;

        //异步上传,通过事件回调获取运行状态

        client.UploadFileAsync(new Uri(url), "POST", fileName);

    }

    catch (Exception ex)

    {

        MessageBox.Show("错误:"+ex.Message);

    }

}

//上传进度事件,修改进度条

void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)

{

    progressBar1.Minimum = ;

    progressBar1.Maximum = (int)e.TotalBytesToSend;

    progressBar1.Value = (int)e.BytesSent;

    progressBar1.Text = e.ProgressPercentage.ToString();

}

//上传完成事件,判断是否上传成功

void client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)

{

    if (e.Error == null)

    {

        progressBar1.Value = progressBar1.Maximum;

        this.label2.Text = "上传成功.";

    }

    else

    {

        MessageBox.Show("上传错误:" + e.Error.Message);

        this.label2.Text = "上传失败.";

    }

}

说明:

1.上传的方法由UploadFile修改为UploadFileAsync,这个方法是异步的,非阻塞。

2.注册WebClient的两个事件UploadFileCompleted和UploadProgressChanged,用于显示进度。

三、大文件上传

大文件传输

1.服务端web.config需要配置最大的请求:

<configuration>

  <system.web>

    <httpRuntime targetFramework="4.5" maxRequestLength="" />

  </system.web>

  <system.webServer>

    <security>

      <requestFiltering>

        <requestLimits maxAllowedContentLength=""/>

      </requestFiltering>

    </security>

  </system.webServer>

</configuration>

2.WebApi代码

[HttpPost]

public String SaveFile()

{

    var request = HttpContext.Current.Request;

    if (request.Files.Count > 0)

    {

        HttpPostedFile file= request.Files.Get(0);

        file.SaveAs(Path.Combine("E:", file.FileName));

    }

    return "1";

}

备注:

1.一般配置为最大2G差不多了,如果比2G还大,建议使用FTP上传吧。