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上传下载文件的更多相关文章
- SFTP上传下载文件、文件夹常用操作
SFTP上传下载文件.文件夹常用操作 1.查看上传下载目录lpwd 2.改变上传和下载的目录(例如D盘):lcd d:/ 3.查看当前路径pwd 4.下载文件(例如我要将服务器上tomcat的日志文 ...
- java web service 上传下载文件
1.新建动态web工程youmeFileServer,新建包com,里面新建类FileProgress package com; import java.io.FileInputStream; imp ...
- rz和sz上传下载文件工具lrzsz
######################### rz和sz上传下载文件工具lrzsz ####################################################### ...
- linux上很方便的上传下载文件工具rz和sz
linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...
- shell通过ftp实现上传/下载文件
直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...
- SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例
本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...
- linux下常用FTP命令 上传下载文件【转】
1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...
- C#实现http协议支持上传下载文件的GET、POST请求
C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...
- HttpClient上传下载文件
HttpClient上传下载文件 java HttpClient Maven依赖 <dependency> <groupId>org.apache.httpcomponents ...
随机推荐
- twemproxy配置
redis多主从,多节点,读写分离架构. nutcracker.yml的twemproxy配置 #redis_main是twemproxy所控制redis主从集群逻辑名称 redis_main: #t ...
- LeetCode 1022. 从根到叶的二进制数之和(Sum of Root To Leaf Binary Numbers)
1022. 从根到叶的二进制数之和 1022. Sum of Root To Leaf Binary Numbers 题目描述 Given a binary tree, each node has v ...
- LeetCode 50. Pow(x, n) 12
50. Pow(x, n) 题目描述 实现 pow(x, n),即计算 x 的 n 次幂函数. 每日一算法2019/5/15Day 12LeetCode50. Pow(x, n) 示例 1: 输入: ...
- 消息中间件——RabbitMQ(十)RabbitMQ整合SpringBoot实战!(全)
前言 1. SpringBoot整合配置详解 publisher-confirms,实现一个监听器用于监听Broker端给我们返回的确认请求:RabbitTemplate.ConfirmCallbac ...
- C++ 用 new 生成一个动态二维数组
//Microsoft Visual Studio 2015 Enterprise //变长二维数组 #include <iostream> #include<iomanip> ...
- 使用uiautomator 截图
1)PC与移动设备建立连接. 2)找到ADB的安装路径,双击启动uiautomator. 路径:D:\ProgramFiles\adt-bundle-windows-x86_64-20140702\a ...
- linux查看系统未被挂载的磁盘空间的方法
原文URL:https://www.cnblogs.com/lemon-flm/p/7597403.html 解决AWS 挂载.解决挂载完重启就消失等问题 linux上的盘和window的有区别,磁盘 ...
- Codeforces Round #415 (Div. 1) (CDE)
1. CF 809C Find a car 大意: 给定一个$1e9\times 1e9$的矩阵$a$, $a_{i,j}$为它正上方和正左方未出现过的最小数, 每个询问求一个矩形内的和. 可以发现$ ...
- 为什么要使用Optional
为什么使用Java Optional Why use Optional? NullPointerException 有个很有名的说法: Null Pointer References: The Bil ...
- python之函数基本使用
函数的定义: 函数是一段具有特定功能的.可重用的语句组,用函数名来表示并通过函数名进行功能调用. 使用函数主要有两个目的:降低编程难度和代码重用. python定义一个函数是通过使用def保留字的方式 ...