当前位置:网站首页>文件的上传和下载
文件的上传和下载
2022-07-27 16:18:00 【猫的幻想曲】
文件的上传和下载,是非常常见的功能。很多的系统中,或者软件中都经常使用文件的上传和下载。 比如:QQ 头像,就使用了上传。 邮箱中也有附件的上传和下载功能。 OA 系统中审批有附件材料的上传
文件上传介绍:
1.要有一个form标签,method=post请求
2.form标签的encType属性值必须为multipart / form-data 值
3.在form标签中使用 input type=file 添加上传的文件
4.编写服务器代码(Servlet程序)接收,处理上传的数据。
encType=multipart/form-data 表示提交的数据,以多段(每一个表单项一个数据段)的形式进行拼接,然后以二进制流的形式发送给服务器。



1.2 commons-fileupload.jar 常用API说明



1.3 fileupload类库的使用:
上传文件的表单:
<body>
<form action="http://localhost:8080/09_EL_JSTL/uploadServlet" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username" /><br>
头像:<input type="file" name="photo" /> <br>
<input type="submit" value="上传">
</form>解析上传的数据的代码
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断上传数据是否是多段数据(只有是多段的数据,才是文件上传的)
if(ServletFileUpload.isMultipartContent(req)){
//创建用于解析上传数据的工具类
FileItemFactory fileItemFactory = new DiskFileItemFactory();
//创建用于解析数据的工具类
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
try {
//解析上传的数据,得到每一个表单项FileItem
List<FileItem> list = servletFileUpload.parseRequest(req);
//循环判断,每一个表单项,是普通循环,还是上传的文件
for(FileItem fileItem : list){
if(fileItem.isFormField()){
//普通表单项
System.out.println("表单项的name属性值:" + fileItem.getFieldName());
//参数UTF-8解决乱码问题
System.out.println("表单项的value属性值:" + fileItem.getString("UTF-8") );
}else{
//上传到文件
System.out.println("表单项的name属性值:" + fileItem.getFieldName());
System.out.println("上传的文件名:" + fileItem.getName());
fileItem.write(new File("E://" + fileItem.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}文件的下载:
下载常用的API说明:

response.setHeader("Content-Disposition", "attachment; fileName=1.jpg");
这个响应头告诉浏览器。这是需要下载的。而 attachment 表示附件,也就是下载的一个文件。fileName=后面,表示下载的文件名。
完成上面的两个步骤,下载文件是没问题了。但是如果我们要下载的文件是中文名的话。你会发现,下载无法正确显示出正确的中文名。
原因是在响应头中,不能包含有中文字符,只能包含 ASCII码。
package com.atguigu.servlet;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
/**
* @Description:
* @Author : Jerry
* @create : 2022-03-17 21:04
*/
public class Download extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取要下载的文件名
String downloadFileName = "d.jpg";
//2.读取要下载的文件内容 (通过ServletContext对象可以读取)
ServletContext servletContext = getServletContext();
// 获取要下载的文件类型
String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
System.out.println("下载的文件类型" + mimeType);
//4.在回传前,通过响应头告诉客户端返回的数据类型
resp.setContentType(mimeType);
//5.还要告诉客户端收到的数据是用于下载使用(还是使用响应头)
//Content-Disposition响应头,表示收到的数据怎么处理
//attachment 表示附件,表示下载使用
//filename= 表示指定下载的文件名
// url编码是把汉字转换成为%xx%xx的格式
resp.setHeader("Content-Disposition","attachment;filename = " + URLEncoder.encode("中国。jpg","UTF-8"));
// / 斜杠被服务器解析表示地址为http://ip:prot/工程名/ 映射 到代码的web目录
InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
//获取响应的输出流
OutputStream outputStream = resp.getOutputStream();
//3.把下载的文件内容回传给客户端
//读取输入流中全部的数据,复制给输出流,输出给客户端
IOUtils.copy(resourceAsStream,outputStream);
}
}
附件中文名乱码问题解决方案:
方案一:URLEncoder 解决 IE 和谷歌浏览器的 附件中文名问题。


BASE64 编解码操作:

支持所有浏览器操作:

因为火狐使用的是 BASE64 的编解码方式还原响应中的汉字。所以需要使用 BASE64Encoder 类进行编码操作。

那么我们如何解决上面两种不同编解码方式呢。我们只需要通过判断请求头中 User-Agent 这个请求头携带过来的浏览器信息即可判断出是什么浏览器。

边栏推荐
- Let's move forward together, the 10th anniversary of Google play!
- The song of the virtual idol was originally generated in this way!
- 「MySQL那些事」一文详解索引原理
- Log4j epic loopholes, big companies like jd.com have been recruited
- Error launching IDEA
- Solve the problem of JSP cascading
- 2021.7.12 internal and external connection of notes
- 20000 words + 30 pictures | what's the use of chatting about MySQL undo log, redo log and binlog?
- 微信小程序多文件上传
- 我人都傻了,CompletableFuture和OpenFegin一起使用竟然报错
猜你喜欢

Uni app label jump

Error launching IDEA

Solve the problem of JSP cascading

2021.7.18笔记 mysql数据类型

I was forced to optimize the API gateway query interface

Preliminary introduction to C miscellaneous lecture linked list

Idea packaging war package and war package location

音乐律动七彩渐变灯芯片--DLT8S04A-杰力科创

2021.8.7 note Servlet

2021.7.30 note index
随机推荐
TypeError: conv2d(): argument ‘padding‘ (position 5) must be tuple of ints, not str【报错】
Complete set of machine learning classification task effect evaluation indicators (including ROC and AUC)
JS tool - Cookie simple encapsulation
Quick access to website media resources
Use mobaxtermto establish a two-tier springboard connection
2021.7.22 note constraints
2021.7.17笔记 mysql其他命令
Installation and deployment of zabbix6.0
你想得到想不到的MySQL面试题都在这了(2022最新版)
Basic operations of MySQL view
RSA encryption and decryption (compatible with wechat applet environment)
What does the number of network request interface layers (2/3 layers) mean
MySQL 主从复制数据不一致,怎么办?
uniapp运行到手机(真机调试)
C basic concepts list description suggestions collection
INSUFFICIENT_ ACCESS_ ON_ CROSS_ REFERENCE_ ENTITY APEX / SALESFORCE
2021.7.18笔记 mysql数据类型
mysql基础语句
全自动吸奶器芯片-DLTAP703SD
2021.7.28 notes