C# WebClient实现文件上传

一、同步上传

文章 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 = 0;
    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="2147483647" />    
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647"/>
      </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上传吧。

转载于:https://www.cnblogs.com/duanjt/p/10578854.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值