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 ...
随机推荐
- 023 Android 自定义Toast控件
1.Toast自定义控件工具类 package com.example.administrator.test62360safeguard.Utils; import android.content.C ...
- Python11之列表2(获取、删除列表元素、列表分片、拷贝)
一.获取列表元素值 列表名 [ 索引值 ] 注:索引值从0开始 nameList = ['詹姆斯','字母哥','乐福','威少','乔治','戴维斯'] nameList[0] '詹姆斯' name ...
- 如何创建etcd双向通信证书
# 安装证书生成软件 wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 -O /usr/bin/cfssl wget https://pkg.cfss ...
- 17 SUMIF函数、countif函数、averagif函数
情景 按买家求他们的消费各是多少. 可以考虑使用分类汇总来做,但这里我们使用函数sumif来做. SUMIF函数 格式:=SUMIF(条件列表,匹配条件,数据区) 该函数这样理解:按照匹配条件,从条件 ...
- c++实现的顺序栈
栈是一种运算受限的线性表,是一种先进后出的数据结构,限定只能在一端进行插入和删除操作,允许操作的一端称为栈顶,不允许操作的称为栈底 因此需要的成员变量如下 int *_stack; //指向申请的空间 ...
- C语言变量和常量
常量 在程序执行过程中,其值不能被改变 常量一般出现在表达式或者赋值语句 利用const 修饰的变量为常量,不可修改 利用define定义的一般为常量,定义时候不需要分号 利用extern修饰的量知识 ...
- Python 内置函数进制转换的用法(十进制转二进制、八进制、十六进制)
使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...
- 搭建一个简单的React项目
我是使用了create-react-app来搭建的基本框架,其中的原理和vue-cli差不多的脚手架.(当然也可以自己配置项目目录,这里我偷了一下懒) npm install -g create-re ...
- Yarn介绍(设计理念与基本架构)
Yarn : 新的计算框架,是一个全局资源管理器,负责整个集群的资源管理和分配 一. Yarn产生背景 Hadoop1.0MR有局限性,概括为以下几个方面 : 扩展性差 可靠性差 资 ...
- 解决 React Native:The development server returned response error code: 404
解决方法: 打开android/app/build.gradle compile 'com.facebook.react:react-native:+' 修改为: compile ("com ...