2019/10/27, .Net c#代码片段

摘要:使用HttpWebRequest向Api接口发送文件,multipart-form数据格式,POST方式

参考地址

/// <summary>
/// HttpWebRequest发送文件
/// </summary>
/// <param name="url">url</param>
/// <param name="filePath">文件路径</param>
/// <param name="paramName">文件参数名</param>
/// <param name="contentType">contentType</param>
/// <param name="nameValueCollection">其余要附带的参数键值对</param>
public static void HttpUploadFile(string url, string filePath, string paramName, string contentType, NameValueCollection nameValueCollection)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
Stream requestStream = request.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nameValueCollection.Keys)
{
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
requestStream.Write(formitembytes, 0, formitembytes.Length);
}
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", paramName, filePath, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
WebResponse webResponse = null;
try
{
webResponse = request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string result = streamReader.ReadToEnd();
}
catch (Exception ex)
{
if (webResponse != null)
{
webResponse.Close();
webResponse = null;
}
}
finally
{
request = null;
}
}

使用

NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "1000");
nvc.Add("name", "user1");
HttpUploadFile("http://your.server.com/upload",@"C:\test\test.jpg", "file", "image/jpeg", nvc);

使用HttpWebRequest POST上传文件的更多相关文章

  1. HttpWebRequest post上传文件

    public static string HttpUploadFile(string url, string path) { // 设置参数 HttpWebRequest request = WebR ...

  2. C# 使用HttpWebRequest通过PHP接口 上传文件

    1:上传文件实例 public void UploadXMLLog(string xmlpath)         {             NameValueCollection nvc = ne ...

  3. HttpWebRequest上传文件(Excel等)

    //上传代码/// <summary> /// 文件上传 /// </summary> /// <param name="strAddress"> ...

  4. ASP.NET上传文件到远程服务器(HttpWebRequest)

    /// <summary> /// 文件上传至远程服务器 /// </summary> /// <param name="url">远程服务地址 ...

  5. C#使用HttpWebRequest和HttpWebResponse上传文件示例

    C#使用HttpWebRequest和HttpWebResponse上传文件示例 1.HttpHelper类: 复制内容到剪贴板程序代码 using System;using System.Colle ...

  6. C#在WinForm下使用HttpWebRequest上传文件

    转自:http://blog.csdn.net/shihuan10430049/article/details/3734398 这段时间因项目需要,要实现WinForm下的文件上传,个人觉得采用FTP ...

  7. 关于HttpWebRequest上传文件

    我们web 操作离不开 http请求响应 HttpWebRequest上传文件也是一样的道理 下面码一些代码: private void UploadFile(string strRequestUri ...

  8. HTTPWebrequest上传文件--Upload files with HTTPWebrequest (multipart/form-data)

    使用HTTPWebrequest上传文件遇到问题,可以参考Upload files with HTTPWebrequest (multipart/form-data)来解决 https://stack ...

  9. ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合

    一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...

随机推荐

  1. 不要让事实妨碍好故事:Facebook精准广告产品与硅谷创业揭秘,4星奇书《混乱的猴子》

        “ 现在,和往常一样,一些有先见之明的学者看到了这一天会再次到来,他们把这次全新的媒体中世纪化过程命名为“第二次口口相传”(Secondary Orality)和“古登堡右括号”(the Gu ...

  2. destoon开发笔记-调取资讯标题图

    今天刚申请博客园的博客,申请速度挺快的.之前我的文章都是发在自己搭建的博客网站,但是是香港服务器,不想续费了,所以就关闭了.之前的数据也没有了,挺可惜了.不过既然加入博客园的大家庭,我就在这每天记录工 ...

  3. wordpress如何添加自增变量(第一篇文章显示摘要后面的只显示标题)

    有时我们在调用文章列表的时候需要在前面添加序号看起来比较整齐,如何实现呢?要想精确的控制每篇文章,我们先在循环前定义一个变量 $ashu_i=1 来计数,变量名随便,然后每循环一次,$ashu_i加1 ...

  4. 排序算法-插入排序(Java)

    package com.rao.linkList; import java.util.Arrays; /** * @author Srao * @className InsertSort * @dat ...

  5. Python实现网络图形化界面多人聊天室 - Linux

    网络图形化界面多人聊天室 - Linux Windows版本:https://www.cnblogs.com/noonjuan/p/12078524.html 在Python实现网络多人聊天室基础上, ...

  6. 通过不断迭代,编写<通过中缀表达式,构造表达式树>的代码

    今天要练习的算法是通过中缀表达式生成表达式树.中缀.前缀.后缀表达式的概念就不赘述了,学习链接:中缀.前缀.后缀表达式. 参考代码学习链接:表达式树—中缀表达式转换成后缀表达式(一). [迭代 ①]: ...

  7. vue 2.0 及 vue 3.0 rem配置

    vue 2.0 配置 rem 首先先安装postcss-px2rem   (百度可以) https://www.jianshu.com/p/e6476bbc2131 npm install postc ...

  8. Ubuntu下安装配置SQLSERVER2017

    摘要自微软官网: https://docs.microsoft.com/zh-cn/sql/linux/quickstart-install-connect-ubuntu 安装步骤: 1. 导入公共秘 ...

  9. Finalizer 导致的OOM

    本文介绍的是Java里一个内建的概念,Finalizer.你可能对它对数家珍,但也可能从未听闻过,这得看你有没有花时间完整地看过一遍java.lang.Object类了.在java.lang.Obje ...

  10. Golang(三)Goroutine原理

    前言 最近用到了一些 Golang 异步编程的地方,感觉 Golang 相对于其他语言(如 Java)对多线程编程的支持非常大,使用起来也非常方便.于是决定了解一下 Goroutine 的底层原理. ...