C#中的multipart/form-data提交文件和参数
作者:qq_34611658 发布时间:2021-09-26 09:40:19
标签:multipart,form-data,提交文件,参数
C# multipart/form-data提交文件和参数
public static string PostJsonData(string url, Dictionary<string, string> dic, string imgfile)
{
string str = "";
try
{
HttpClient client = new HttpClient();
var postContent = new MultipartFormDataContent();
string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
string image_file_Type="faceImage";
postContent.Add(new ByteArrayContent(File.ReadAllBytes(imgfile)), image_file_Type, imgfile);
foreach (var key in dic.Keys)
{
postContent.Add(new StringContent(dic[key].ToString()), key);
}
HttpResponseMessage response = client.PostAsync(url, postContent).Result;
str = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
Log.Print("PostJsonData:" + ex.ToString());
}
return str;
}
C# POST multipart/form-data案例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using XingcOpen.ILS.Business.Interface;
using XingcOpen.ILS.Core.Model;
using XingcOpen.ILS.Core.Log;
using XingcOpen.ILS.Business.Config.Module;
using XingcOpen.ILS.Business.Config;
using System.Threading;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Windows.Forms;
namespace XingcOpen.ILS.Business.ExpressSystemApi.Client
{
/// <summary>
/// 韩国图片上报接口
/// </summary>
class HanGuoLogisticsPic : ISendPackageInfo
{
public bool CheckProcessHasRun()
{
throw new NotImplementedException();
}
UserConfigInfo config = UserConfigHelper.GetInstance().userConfig;
private static object _loc = new object();
private Thread DSuPicUpload;
public bool CheckTicketNumHasEffective(string ticketsNum)
{
throw new NotImplementedException();
}
public CommonResult GeneralSendTicketsNumAndPackageWeight(TicketInfo info)
{
throw new NotImplementedException();
}
public bool SendTicketsNumAndPackageWeight(string barcode, double weight, double length, double width, double height, double volume)
{
//定义图片绝对路径
//var ListImage = config.PicSavePath + @"\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + barcode + ".jpg";
try
{
图片上传
DSuPicUpload = new Thread(() => UploadPic(barcode));
DSuPicUpload.Start();
return true;
}
catch (Exception ex)
{
Logger<HanGuoLogisticsPic>.Error("线程启动异常," + ex.Message);
return false;
}
}
public T SendTicketsNumAndPackageWeight<T>(Dictionary<string, object> packageDic)
{
throw new NotImplementedException();
}
#region 图片上报接口
private void UploadPic(string barcode)
{
while (true)
{
if (config.IsSavePic == 1)
{
//上传图片
DoLocalImgUpload(Path.Combine(config.PicSavePath, DateTime.Now.ToString("yyyyMMdd")), barcode);
DoLocalImgUpload(Path.Combine(config.PicSavePath, DateTime.Now.AddDays(-1).ToString("yyyyMMdd")), barcode);
}
Thread.Sleep(3000);
}
}
public void DoLocalImgUpload(string picFilepath, string barcode)
{
try
{
if (Directory.Exists(picFilepath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(picFilepath);
//取图片文件夹下的1分钟之前的图片的前5张(按创建时间排序)
//防止文件被占用
lock (_loc)
{
var topfiles = directoryInfo.EnumerateFiles().
Where(p => p.CreationTime <= DateTime.Now.AddMinutes(-1)).
OrderBy(f => f.CreationTime).
Take(5).ToList();
// topfiles.Distinct();
topfiles.OrderByDescending(x => x.FullName).Distinct();
if (topfiles.Count > 0)
{
//循环执行上传
foreach (var fileInfo in topfiles)
// for (var i = 0; i < topfiles.Count; i++)
{
Logger<HanGuoLogisticsPic>.Debug("topfiles.count:" + topfiles.Count + " fileInfo:" + fileInfo.FullName);
UploadLocalByName(fileInfo.FullName, barcode);
//topfiles.Remove(fileInfo);
}
topfiles.Clear();
Thread.Sleep(1000);
Logger<HanGuoLogisticsPic>.Debug("图片上传线程循环上传中!");
}
}
}
}
catch (Exception ex)
{
Logger<HanGuoLogisticsPic>.Error(".图片文件上传发生异常!", ex);
}
}
public void UploadLocalByName(string picFilepath, string barcode)
{
string url = @"http://www.kwaiden.com/SendPackageInfo/ApiPhoto_I.asp";
try
{
Logger<HanGuoLogisticsPic>.Debug("picFilepath:" + picFilepath);
if (File.Exists(picFilepath))
{
int pos = picFilepath.LastIndexOf("\\");
string name = picFilepath.Substring(pos + 1);
string nums = name.Replace(".jpg", "");
//string userPhoto = string.Empty;
//byte[] bytes = File.ReadAllBytes(picFilepath);
//userPhoto = Convert.ToBase64String(bytes);
//userPhoto = userPhoto.Replace("+", "%2B");
if (UploadImages(nums, name, picFilepath, url, barcode))
{
//上传完是否需要删除?
File.Delete(picFilepath);
}
}
}
catch (Exception ex)
{
Logger<HanGuoLogisticsPic>.Error(".图片文件上传发生异常!", ex);
}
}
public bool UploadImages(string code, string name, string picFilepath, string url, string barcode)
{
try
{
string result = SendData(picFilepath, name, url, barcode, null, null);
var i = JObject.Parse(result);
if (i["result"].ToString().Trim() == "true")
{
//播放声音文件
string strPath = Path.Combine(Application.StartupPath, @"config\sound") + "\\" + "Right.wav";
if (File.Exists(strPath))
{
System.Media.SoundPlayer sndPlayer2 = new System.Media.SoundPlayer(strPath);
sndPlayer2.Play();
}
else
{
Logger<HanGuoLogistics>.Error("PlaySoundSendSuccess。 不存在声音文件:" + strPath);
}
return true;
}
else
{
//播放声音文件
string strPath = Path.Combine(Application.StartupPath, @"config\sound") + "\\" + "Wrong.wav";
if (File.Exists(strPath))
{
System.Media.SoundPlayer sndPlayer2 = new System.Media.SoundPlayer(strPath);
sndPlayer2.Play();
}
else
{
Logger<HanGuoLogistics>.Error("PlaySoundSendSuccess。 不存在声音文件:" + strPath);
}
return false;
}
}
catch (Exception e)
{
Logger<HanGuoLogisticsPic>.Error("上传图片异常 " + e);
}
return false;
}
public string SendData(string picFilepath, string name, string url, string barcode, string workConsole, string destination)
{
var fileContent1 = new ByteArrayContent(File.ReadAllBytes(picFilepath));
fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("file")
{
FileName = name
};
var postContent = new MultipartFormDataContent();
postContent.Add(new StringContent(barcode), "ticketsNum");
postContent.Add(fileContent1);//图片文件
postContent.Add(new StringContent(workConsole), "workConsole");
postContent.Add(new StringContent(destination), "destination");
Logger<HanGuoLogisticsPic>.Debug("向"+config.HttpPostApiAddr+"发送数据"+JsonConvert.SerializeObject(postContent));
string httpResult = GetHttpPostResponse(url, postContent);
Logger<HanGuoLogisticsPic>.Debug("接收" + config.HttpPostApiAddr + "返回数据" + httpResult);
return httpResult;
}
private string GetHttpPostResponse(string url, MultipartFormDataContent postData)
{
string result = "";
//form表单格式传参
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.PostAsync(url, postData).Result;
result = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
result = ex.Message;
}
Logger<HanGuoLogisticsPic>.Debug($"HanGuoLogistics 返回数据:{result}");
return result;
}
/// <summary>
/// 参数上报
/// </summary>
public class ImageInfo
{
public string ticketsNum { get; set; }
public string file { get; set; }
public string workConsole { get; set; }
public string destination { get; set; }
}
/// <summary>
/// 返回信息
/// </summary>
public class ImageResult
{
public bool result { get; set; }
public string message { get; set; }
}
#endregion
}
}
来源:https://blog.csdn.net/qq_34611658/article/details/105530402


猜你喜欢
- 在网上找了半天,说的都没有解决我的问题,我自己花了点时间在idea中找到并解决了问题,希望可以帮助到大家。File---->setti
- Flyweight定义:避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类)。为什么使用共享模式/享元模式面向对象语言的
- 以下内容给大家介绍Android数据存储提供了五种方式:1、SharedPreferences2、文件存储3、SQLite数据库4、Cont
- 概述 这是一个自定义色盘,根据点,直线和圆的几何学加上hsv颜色模型完成技术点几何:圆的标准方程式:(x-a)²
- 本文实例讲述了Android开发之DatePickerDialog、TimePickerDialog时间日期对话框用法。分享给大家供大家参考
- maven配置阿里云镜像打开maven配置文件,找到标签,添加如下:<mirrors> <mirror>
- 最近在做数据挖掘的课程设计,需要将数据分析的结果很直观的展现给用户,这就要用到数据统计图,要实现这个功能就需要几个第三方包了:1. 
- 关于死信队列在大多数的MQ中间件中,都有死信队列的概念。死信队列同其他的队列一样都是普通的队列。在RabbitMQ中并没有特定的“死信队列”
- 1 初识Mybatis-Plus MyBatis-Plus简称 MP,是一个 MyBatis的增强工具,在MyBatis的基础上只做增强不
- 这两天学习了使用Path绘制贝塞尔曲线相关,然后自己动手做了一个类似QQ未读消息可拖拽的小气泡,效果图如下:最终效果图接下来一步一步的实现整
- 1. 引入当我们编写一个类时,其实就是在描述其对象的属性和行为,而并没有产生实质上的对象, 只有通过new关键字才会产生出对象,这时系统才会
- 本文实例讲述了C++二分查找(折半查找)算法。分享给大家供大家参考,具体如下:二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好
- 在android平板上用webview打开一个网页,调用里面的javascript方法,同时相互传参。网上例子很少啊,基本都不能获取返回值,
- 一、自己封装URLConnection 连接请求类 public void downloadFile1() { try{ &nb
- 本文实例讲述了C#编程获取各种电脑硬件信息的方法。分享给大家供大家参考,具体如下:获取CPU编号:ManagementClass mc =
- 本文实例展示了C#中this指针的用法,对于初学者进一步牢固掌握C#有很大帮助,具体内容如下:一、this指针是什么:这里有一些面向对象编程
- 前言在之前的Spring Boot基础教程系列中,已经通过《Spring Boot中使用@Async实现异步调用》一文介绍过如何使用@Asy
- start方法和run方法$start()$方法用来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到$cpu$时间片,就
- Java基本类型与byte数组之间相互转换,刚刚写的package cn.teaey.utils;import java.nio.chars
- 大多数android程序员应该都知道genymotion是一个不错的模拟器,体积小巧,启动速度快。相关的博客也比较多,但是一直以来无法解决a