当前位置:网站首页>Uploading and downloading of files
Uploading and downloading of files
2022-07-27 18:50:00 【Fantasia of the cat】
File upload and download , Is a very common function . In a lot of systems , Or file upload and download are often used in software . such as :QQ Head portrait , Upload... Is used . The mailbox also has the function of uploading and downloading attachments . OA Upload of approved attachment materials in the system
File upload Introduction :
1. Want to have one form label ,method=post request
2.form Labeled encType Property value must be multipart / form-data value
3. stay form Use in Tags input type=file Add uploaded files
4. Write server code (Servlet Program ) receive , Processing uploaded data .
encType=multipart/form-data Represents submitted data , With multiple segments ( Each form item has a data segment ) In the form of splicing , It's then sent to the server as a binary stream .



1.2 commons-fileupload.jar Commonly used API explain



1.3 fileupload Use of class library :
Form to upload file :
<body>
<form action="http://localhost:8080/09_EL_JSTL/uploadServlet" method="post" enctype="multipart/form-data">
user name :<input type="text" name="username" /><br>
Head portrait :<input type="file" name="photo" /> <br>
<input type="submit" value=" Upload ">
</form>Code for parsing uploaded data
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Judge whether the uploaded data is multi segment data ( It's just multi segment data , It's the files that are uploaded )
if(ServletFileUpload.isMultipartContent(req)){
// Create a tool class for parsing uploaded data
FileItemFactory fileItemFactory = new DiskFileItemFactory();
// Create tool classes for parsing data
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
try {
// Parsing uploaded data , Get every form item FileItem
List<FileItem> list = servletFileUpload.parseRequest(req);
// Circular judgement , Every form item , Is a normal cycle , Or uploaded files
for(FileItem fileItem : list){
if(fileItem.isFormField()){
// Common form items
System.out.println(" Of the form item name Property value :" + fileItem.getFieldName());
// Parameters UTF-8 Solve the mess
System.out.println(" Of the form item value Property value :" + fileItem.getString("UTF-8") );
}else{
// Upload to file
System.out.println(" Of the form item name Property value :" + fileItem.getFieldName());
System.out.println(" Uploaded file name :" + fileItem.getName());
fileItem.write(new File("E://" + fileItem.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}Download files :
Download commonly used API explain :

response.setHeader("Content-Disposition", "attachment; fileName=1.jpg");
This response header tells the browser . This is what you need to download . and attachment Means attachment , That is, a file downloaded .fileName= Back , Indicates the name of the downloaded file .
Complete the above two steps , There is no problem downloading files . But if the file we want to download is Chinese . You'll find that , The download cannot display the correct Chinese name correctly .
The reason is that in the response header , Cannot contain Chinese characters , Can only contain ASCII code .
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. Get the name of the file to download
String downloadFileName = "d.jpg";
//2. Read the contents of the file to be downloaded ( adopt ServletContext Object can read )
ServletContext servletContext = getServletContext();
// Get the file type to download
String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
System.out.println(" Type of file downloaded " + mimeType);
//4. Before returning , The response header tells the client the type of data returned
resp.setContentType(mimeType);
//5. Also tell the client that the data received is for download ( Or use the response header )
//Content-Disposition Response head , How to handle the received data
//attachment Means attachment , It means to download and use
//filename= Indicates the file name of the specified download
// url Coding is the conversion of Chinese characters into %xx%xx The format of
resp.setHeader("Content-Disposition","attachment;filename = " + URLEncoder.encode(" China .jpg","UTF-8"));
// / The slash is parsed by the server to indicate that the address is http://ip:prot/ project name / mapping To code web Catalog
InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
// Get the output stream of the response
OutputStream outputStream = resp.getOutputStream();
//3. Send the downloaded file back to the client
// Read all the data in the input stream , Copy to the output stream , Output to the client
IOUtils.copy(resourceAsStream,outputStream);
}
}
Attachment Chinese name garbled problem solution :
Scheme 1 :URLEncoder solve IE And Google browser Attachment Chinese name question .


BASE64 Encoding and decoding operations :

Support all browser operations :

Because it uses BASE64 Restore the Chinese characters in the response by encoding and decoding . So we need to use BASE64Encoder Class for encoding operations .

So how do we solve the above two different encoding and decoding methods . We just need to judge the request header User-Agent The browser information carried by the request header can determine what browser it is .

边栏推荐
- 全身多功能按摩仪芯片-DLTAP602SD
- 订单超时取消 及 按类别查询商品
- XML learning Day1: XML / jsup parser / selector /xpath selector
- 机器学习——SVM训练集只有一类标签数据而引发的错误
- The song of the virtual idol was originally generated in this way!
- js实现简易表单验证与全选功能
- 2021.8.1 notes DBA
- 你想得到想不到的MySQL面试题都在这了(2022最新版)
- Openstack login dashboard prompt authentication error
- Hbuilder submission code
猜你喜欢

面试官:你觉得你最大的缺点是什么?

知识图谱 — pyhanlp实现命名体识别(附命名体识别代码)

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

你有没有在MySQL的order by上栽过跟头

全身多功能按摩仪芯片-DLTAP602SD

搭建一个简单的知识问答系统

解决Jsp级联问题

Error launching IDEA

【npm】 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。

The combination of text and words perfectly explains the implementation process of MySQL logical backup
随机推荐
Complete set of machine learning classification task effect evaluation indicators (including ROC and AUC)
How to realize the full-text content retrieval of word, PDF and txt files?
Labels such as {@code}, {@link} and < P > in the notes
全身多功能按摩仪芯片-DLTAP602SD
Wechat applet wxacode.getunlimited generates applet code
RuntimeError: output with shape [1, 256, 256] doesn‘t match the broadcast shape [3, 256, 256]【报错】
What if MySQL database forgets its password???
Set the arc button to be displayed in the middle
2021.7.13 note sub query
Uni app label jump
Modify placeholder style in input
Log4j epic loopholes, big companies like jd.com have been recruited
全自动吸奶器芯片-DLTAP703SD
连接查询和子查询
Basic operations of MySQL view
智能失眠治疗仪产品-DLT8P68SA-杰力科创
Uni app form submit button send request
[yuntu said] 249 mobile application security service - app's physical examination center, comprehensive testing, safe on the road!
修改input中placeholder样式
Ant privacy computing innovation tee technology has won academic recognition