.NET 文件上传和文件接收
有时候,我们需要在后台端发起向指定的“文件接收接口”的文件传输请求,可以采用HttpWebRequest方式实现文件传输请求。
1、HttpWebRequest文件传输请求的代码如下:
其中,url为外部的文件接收接口,url中可以跟多个参数,如: http:project/Weixin/SaveUploadFile?path={0}
filePath为待上传文件的物理路径
/// <summary>
/// 传输文件到指定接口
/// </summary>
/// <param name="url"></param>
/// <param name="filePath">文件物理路径</param>
/// <returns></returns>
public static string PostFile(string url, string filePath)
{
// 初始化HttpWebRequest
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url); // 封装Cookie
Uri uri = new Uri(url);
Cookie cookie = new Cookie("Name", DateTime.Now.Ticks.ToString());
CookieContainer cookies = new CookieContainer();
cookies.Add(uri, cookie);
httpRequest.CookieContainer = cookies; if (!File.Exists(filePath))
{
return "文件不存在";
}
FileInfo file = new FileInfo(filePath); // 生成时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", strBoundary)); // 填报文类型
httpRequest.Method = "Post";
httpRequest.Timeout = * ;
httpRequest.ContentType = "multipart/form-data; boundary=" + strBoundary; // 封装HTTP报文头的流
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append(Environment.NewLine);
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(file.Name);
sb.Append("\"");
sb.Append(Environment.NewLine);
sb.Append("Content-Type: ");
sb.Append("multipart/form-data;");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString()); // 计算报文长度
long length = postHeaderBytes.Length + file.Length + boundaryBytes.Length;
httpRequest.ContentLength = length; // 将报文头写入流
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(postHeaderBytes, , postHeaderBytes.Length);
//文件流循环写入
byte[] buffer = new byte[];
int bytesRead = ;
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
requestStream.Write(buffer, , bytesRead);
}
} // 将报文尾部写入流
requestStream.Write(boundaryBytes, , boundaryBytes.Length);
// 关闭流
requestStream.Close(); using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
{
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
var rs = sr.ReadToEnd();
return rs;
//Console.WriteLine("反馈结果" + responseString);
}
}
2、文件接收端:url接口代码如下
其中,JsonResultData类为自身项目中的一个传输类;
Base.Config.BConfig.GetConfigToString(path) 为自身项目中在配置文件中根据键获得值的方法。
/// <summary>
/// 保存平台端传来的文件
/// </summary>
/// <param name="path"></param>
/// <param name="file"></param>
/// <returns></returns>
public ActionResult SaveUploadFile(string path, HttpPostedFileBase file)
{
JsonResultData result = new JsonResultData(); try
{
string myPath = Base.Config.BConfig.GetConfigToString(path);//配置文件中读取路径 if (string.IsNullOrWhiteSpace(myPath))
{
throw new Exception("未配置附件存放路径,请联系管理员配置"+path);
}
if (Directory.Exists(myPath) == false)
{
Directory.CreateDirectory(myPath);
} file.SaveAs(myPath + "\\" + file.FileName);
result.IsSuccess = true;
result.Message = "文件保存成功!"+path;
}
catch (Exception ex)
{
result.IsSuccess = false;
result.Message = ex.Message;
BLog.Write(BLog.LogLevel.WARN, "上传附件出错:" + ex.ToString());
}
return Json(result, JsonRequestBehavior.AllowGet);
}
.NET 文件上传和文件接收的更多相关文章
- django设置并获取cookie/session,文件上传,ajax接收文件,post/get请求及跨域请求等的方法
django设置并获取cookie/session,文件上传,ajax接收文件等的方法: views.py文件: from django.shortcuts import render,HttpRes ...
- SpringMVC文件上传 Excle文件 Poi解析 验证 去重 并批量导入 MYSQL数据库
SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库 /** * 业务需求说明: * 1 批量导入成员 并且 自主创建账号 * 2 校验数据格式 且 重复导入提示 已被 ...
- struts2文件上传,文件类型 allowedTypes
struts2文件上传,文件类型 allowedTypes 1 '.a' : 'application/octet-stream', 2 '.ai' : 'application/postscript ...
- SpringMVC单文件上传、多文件上传、文件列表显示、文件下载(转)
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 本文详细讲解了SpringMVC实例单文件上传.多文件上传.文件列表显示.文件下载. 本文工程 ...
- webAPI文件上传时文件过大404错误的问题
背景:最近公司有个需求,外网希望自动保存数据到内网,内网有2台服务器可以相互访问,其中一台服务器外网可以访问,于是想在 这台服务器上放个中转的接口.后来做出来以后测试发现没有问题就放线上去了,不顾发现 ...
- 文件上传fileupload文件接收
form表单提交数据到servlet后,使用fileupload进行接收. fileupload 是由 apache 的 commons 组件提供的上传组件.它最主要的工作就是帮我们解析 reques ...
- form表单文件上传 servlet文件接收
需要导入jar包 commons-fileupload-1.3.2.jar commons-io-2.5.jar Upload.Jsp代码 <%@ page language="jav ...
- spring mvc文件上传(单个文件上传|多个文件上传)
单个文件上传spring mvc 实现文件上传需要引入两个必须的jar包 1.所需jar包: commons-fileupload-1.3.1.jar ...
- PHP表单处理、会话管理、文件上传、文件处理、执行函数(10.8 第十六天)
表单处理 服务器接收用户发过来的数据方式: $_GET 接收用户以GET方式发过来的数据 $_POST 接收用户以POST方式发过来的数据 $_COOKIE 接收用户COOKIE $_REQUEST ...
- struts2实现文件上传(多文件上传)及下载
一.要实现文件上传,需在项目中添加两个jar文件 二.上传准备的页面 注:必须植入enctype="multipart/form-data"属性,以及提交方式要设置成post &l ...
随机推荐
- python基础语法2 流程控制 if,while,for
if语句: 什么是if? 主要是用于判断事物得对错,真假,是否可行 语法结构: python是通过缩进来决定代码的归属 pep8: 缩进一定是四个空格 tab键 if 条件: 代码块 .... ... ...
- MapReduce的核心运行机制
MapReduce的核心运行机制概述: 一个完整的 MapReduce 程序在分布式运行时有两类实例进程: 1.MRAppMaster:负责整个程序的过程调度及状态协调 2.Yarnchild:负责 ...
- Tomcat 禁用不安全的 HTTP 请求模式及测试
WebDAV (Web-based Distributed Authoring and Versioning) 一种基于 HTTP 1.1协议的通信协议.它扩展了HTTP 1.1,在GET.POST. ...
- flux沉思录:面向store和通信机制的前端框架
一.综述 Flux 被用来描述“单向”的数据流,且包含某些特殊的事件和监听器. 响应式编程是一种面向数据流和变化传播的编程范式 flux是响应式编程的一种? Flux 在本质上采用了模型-视图-控制器 ...
- 通过100张图一步步理解CNN
https://blog.csdn.net/v_july_v/article/details/79434745 Youtube上迄今为止最好的卷积神经网络快速入门教程 https://www.bili ...
- [React] Fetch Data with React Suspense
Let's get started with the simplest version of data fetching with React Suspense. It may feel a litt ...
- ABP 03 解决 编辑User报错
1.编辑用户时,报错.后面有跟解决方案. 解决方案1: 2.导致出错的原因是这样的,这里的功能是请求服务端的html页面,渲染后显示编辑页面. 关键点是默认参数那儿 路径:\aspnet-core\s ...
- 使用Visual Studio Code编辑Processing
最近想弄Sublime Text 3写Processing,但由于各种不知名原因导致无法编译,就想着换自去年以来超火的VScode试一下,还真给我试成功了. 1.下载https://code.visu ...
- JDBC-select练习&jdbc工具类&数据库登录案例
一.select练习 1.说明 练习: * 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回. 1. 定义Emp类 2. 定义方法 public List<Emp> fi ...
- 第9期《jmeter接口自动化实战》零基础入门!
2019年 第9期<jmeter接口自动化实战>课程,12月6号开学! 上课方式:QQ群视频在线教学 本期上课时间:12月6号-1月18号,每周五.周六晚上20:00-22:00 报名费: ...