tomcat实现文件上传下载
修改web.xml
post请求
代码实现
- 修改Tomcat中的server.xml
- 修改web.xml
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>12345678910111213
实现服务端的处理
Accept-Language: zh-cn
Host: 192.168.24.56
Content-Type:multipart/form-data;boundary=【这里随意设置】
User-Agent: WinHttpClient
Content-Length: 3693
Connection: Keep-Alive123456789
Content-Disposition: form-data;name="file1";filename="C://E//a.png"
Content-Type:application/octet-stream
--【这里随意设置】--1234567
try {
final String newLine = "\r\n";
//数据分隔线
final String BOUNDARY = "【这里随意设置】";//可以随意设置,一般是用 ---------------加一堆随机字符
//文件结束标识
final String boundaryPrefix = "--";
URL url = new URL("http://localhost:8070/secondary/HandleFile");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置为POST情
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
//conn.setDoInput(true);/不必加,默认为true
//conn.setUseCaches(false);//用于设置缓存,默认为true,不改也没有影响(至少在传输单个文件这里没有)
//关于keep-alive的说明:https://www.kafan.cn/edu/5110681.html
//conn.setRequestProperty("connection", "Keep-Alive");//现在的默认设置一般即为keep-Alive,因此此项为强调用,可以不加
//conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows Nt 5.1; SV1)");//用于模拟浏览器,非必须
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//这里是Charset,网上大多都是Charsert???我的天,笑哭。不过好像没什么影响...不知道哪位大佬解释一下
conn.setRequestProperty("Charset", "UTF-8");
OutputStream out = new DataOutputStream(conn.getOutputStream());
//写参数头
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix)//表示报文开始
.append(BOUNDARY)//添加文件分界线
.append(newLine);//换行,换行方式必须严格约束
//固定格式,其中name的参数名可以随意修改,只需要在后台有相应的识别就可以,filename填你想要被后台识别的文件名,可以包含路径
sb.append("Content-Disposition: form-data;name=\"file\";")
.append("filename=\"").append(fileName)
.append("\"")
.append(newLine);
sb.append("Content-Type:application/octet-stream");
//换行,为必须格式
sb.append(newLine);
sb.append(newLine);
out.write(sb.toString().getBytes());
System.out.print(sb);
File file = new File(fileName);
DataInputStream in = new DataInputStream(new FileInputStream(
file));
byte[] bufferOut = new byte[1024];
int bytes = 0;
//每次读1KB数据,并且将文件数据写入到输出流中
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
out.write(newLine.getBytes());
System.out.print(new String(newLine.getBytes()));
sb = new StringBuilder();
sb.append(newLine)
.append(boundaryPrefix)
.append(BOUNDARY)
.append(boundaryPrefix)
.append(newLine);
// 写上结尾标识
out.write(sb.toString().getBytes());
System.out.println(sb);
//输出结束,关闭输出流
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
处理文件信息,包括识别文件名,识别文件类型(由用户定义,而不是文件后缀)
存储到本地(服务器端硬盘)
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//注意导的包
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//输出到客户端浏览器
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sup = new ServletFileUpload(factory);//这里要将factory传入,否则会报NullPointerException: No FileItemFactory has been set.
try{
List<FileItem> list = sup.parseRequest(request);
for(FileItem fileItem:list){
System.out.println(fileItem.getFieldName()+"--"+fileItem.getName());
if(!fileItem.isFormField()){
if("file".equals(fileItem.getFieldName())){
//获取远程文件名
String remoteFilename = new String(fileItem.getName().getBytes(),"UTF-8");
File remoteFile = new File(remoteFilename);
File locate = new File("C://E//download/",remoteFile.getName());
locate.createNewFile(); //创建新文件
OutputStream ous = new FileOutputStream(locate); //输出
try{
byte[] buffer = new byte[1024]; //缓冲字节
int len = 0;
while((len = ins.read(buffer))>-1)
ous.write(buffer, 0, len);
}finally{
ous.close();
ins.close();
}
}
}
}
}catch (FileUploadException e){}
out.flush();
out.close();
---------------------
作者:Sailist
来源:CSDN
原文:https://blog.csdn.net/sailist/article/details/81083205
版权声明:本文为博主原创文章,转载请附上博文链接!
tomcat实现文件上传下载的更多相关文章
- SpringMVC文件上传下载
在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...
- 阿里云负载均衡SLB的文件上传下载问题解决
Nfs同步文件夹配置 问题描述 : javaweb应用部署到云服务器上时,当服务器配置了SLB负载均衡的时候,多台服务器就会造成文件上传下载获取不到文件的错误, 解决办法有:1.hdfs 2.搭建f ...
- 17.[CVE-2017-12615]Tomcat任意文件上传漏洞
[CVE-2017-12615] Tomcat任意文件上传漏洞 首先先贴出wooyun上的一个案例:http://wooyun.jozxing.cc/static/bugs/wooyun-2015-0 ...
- Spring Boot2(十四):单文件上传/下载,文件批量上传
文件上传和下载在项目中经常用到,这里主要学习SpringBoot完成单个文件上传/下载,批量文件上传的场景应用.结合mysql数据库.jpa数据层操作.thymeleaf页面模板. 一.准备 添加ma ...
- SpringMVC文件上传下载(单文件、多文件)
前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...
- SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)
SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...
- Struts的文件上传下载
Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- Selenium2学习-039-WebUI自动化实战实例-文件上传下载
通常在 WebUI 自动化测试过程中必然会涉及到文件上传的自动化测试需求,而开发在进行相应的技术实现是不同的,粗略可划分为两类:input标签类(类型为file)和非input标签类(例如:div.a ...
随机推荐
- ding
Import "shanhai.lua"Dim currHour,currMinute,currSecondDim mmRnd = 0Dim sumFor=Int(ReadUICo ...
- log4j向指定文件输出日志
一.log4j.properties中的配置 log4j.logger.cache=INFO,ERROR,batchFile log4j.addivity.batchFile=false log4j. ...
- python---pth包路径
为依赖包添加环境变量 (这一步很关键)PYTHONPATH C:\tensorflow\models\research;C:\tensorflow\models\research\slim6.然后并没 ...
- github.com连接超时
https://blog.csdn.net/hanchao5272/article/details/79393393 1.错误信息 之前github都能用,但是今天git clone的时候居然连不上 ...
- OSI七层模型对应功能及协议
前言 OSI七层模型:纯理论模型,所有实际设备和协议都不能对应理论模型. 每一层对应着实际的设备 物理层:中继器.集线器.双绞线 数据链路层:网桥.以太网交换机.网卡 网路层:路由器.三层交换机 传输 ...
- golang之结构体结构体嵌入和匿名成员
考虑一个二维的绘图程序,提供了一个各种图形的库,例如矩形.椭圆形.星形和轮形等几何形状.这里是其中两个的定义: type Circle struct { X, Y, Radius int } type ...
- WUSTOJ 1337: Car race game(C)树状数组,离散化
题目链接:1337: Car race game 参考资料:⑴ Car race game 树状数组 棋煜,⑵ 树状数组,⑶ 离散化 补充资料:⑴ qsort,⑵ 二分查找 Description B ...
- Git学习记录(一)
本篇文章介绍Git的本地使用 Git是什么? Git是世界上最先进的分布式版本控制系统. 那么什么是版本控制系统? 我们来举个例子,假设我创建了一个项目Project.1,里面写了一个README.t ...
- Scala 算法案例
移除第一个负数之后的所有负数 // 构建数组 val a = ArrayBuffer[Int]() a += (1, 2, 3, 4, 5, -1, -3, -5, -9) // 每发现一个第一个负数 ...
- PowerShell自动部署ASP.NET Core程序到 IIS
Windows PowerShell 是一种命令行外壳程序和脚本环境,使命令行用户和脚本编写者可以利用 .NET Framework的强大功能.有关于更多PowerShell的信息,可参阅百度词条 接 ...