当前位置:网站首页>Native servlet - upload & download of files
Native servlet - upload & download of files
2022-06-12 19:05:00 【Su Tong Na】
List of articles
File upload and download
1. File upload details
Want to have one form label ,method-post request ( because get Limited length )
form Attributes of the tag
encTypeValue must be multipart/form-dataIndicates that the submitted data is multi ended ( Each form item has a data segment ) In the form of splicing , It's then sent to the server as a binary stream
stay form Use in Tags
input type="file"Add uploaded filesWrite server code (Servlet receive ), Accept and process uploaded data
Upload files http Request information :
Request header :Content-Type: multipart/form-data; boundary=------WebKitFormBoundaryCd3g75eOt35olUs7
analysis :
Content-TypeIndicates the type of data submittedmultipart/form-dataMeans to submit the server in the form of a streamboundaryThe separator for each piece of data , value :----WebKitFormBoundarylXiF4fEzpo9c8L4pIt is randomly generated by the browser every time , It is the delimiter of each piece of data . In each paragraph The first line is the description of the form item , Then there is a blank line , Here are the submitted values .
Request body :
------WebKitFormBoundaryCd3g75eOt35olUs7
Content-Disposition: form-data; name="username"
zhu
------WebKitFormBoundaryCd3g75eOt35olUs7
Content-Disposition: form-data; name="photo"; filename="head.jpg"
Content-Type: image/jpeg
File information ( For a long time, we have omitted )
------WebKitFormBoundaryCd3g75eOt35olUs7--
Because the client submits by stream , So we need to get by stream , You can't do that : req.getParameter("username");
Proper use :
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(" Upload successful ");
ServletInputStream inputStream = req.getInputStream(); // First get Byte input stream
byte[] buffer = new byte[1024]; // buffer
int readCount = 0;
while ((readCount = inputStream.read(buffer)) != -1) {
// All the request bodies above are printed out
System.out.println(new String(buffer, 0, readCount));
}
}
2. Upload files
This kind of file upload ( Commonly used ) There's a lot of Third party offers good API We have used , It can help us parse the data we receive .
for example :commons-fileupload-1.2.1.jar ( Depend on commons-io-1.4.jar)
Import two jar package
analysis
Key classes :
ServletFileUploadclass : Used to parse the uploaded dataFileItemclass : Every form item
//ServletFileUpload The method in
// Judge whether the currently uploaded data is in multi terminal format , It's not that it can't be resolved
public boolean ServletFileUpload.isMultipartContent(HttpServletRequest req)
// Parsing uploaded data ,FileItem Represents each form item
public List<FileItem> parseRequest(HttpServletRequest req)
//FileItem Medium method
// Determine whether the current form item is a common form item or a file upload type ,true It means ordinary
public boolean isFormField()
// Get form item name Property value
public String getFieldName()
// Get the value of the current form item
public String getString() // Passable character set , Prevent confusion code , In limine req.setCharacterEncoding("UTF-8"); It's OK
// Get the uploaded file name
public String getName()
// Write the uploaded file Parameters file The disk location pointed to
public void write(File file)
Servlet Upload file example :
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8"); // Prevent confusion code
resp.setContentType("text/html; charset=utf-8");
String savePath = getServletContext().getRealPath("/WEB-INF/uploadFile"); // Saved path
// First, judge whether the uploaded data is multi segment data
if (ServletFileUpload.isMultipartContent(req)) {
FileItemFactory fileItemFactory = new DiskFileItemFactory(); // establish FileItemFactory Factory implementation class ,
// Create a tool class for parsing uploaded data
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
try {
List<FileItem> list = servletFileUpload.parseRequest(req); // analysis , Get every form item
for (FileItem fileItem : list) {
if (fileItem.isFormField()) {
// Common form items
System.out.print(" Of the form item name Property value :" + fileItem.getFieldName());
System.out.println(" Of the form item value:" + fileItem.getString("UTF-8"));
} else {
// file type
System.out.print(" Of documents name Property value :" + fileItem.getFieldName());
System.out.println(" Uploaded file name :" + fileItem.getName());
// It is usually saved to a directory that users cannot access directly File.separator Is the system default path separator ,win Next is /
// ( The following is saved to the deployment directory , Saved to the server )
// It can be used UUID Ensure the uniqueness of the file name , Prevent file overlay .
// Prevent too many single directory files from affecting the reading and writing speed , You can also use a directory generation algorithm to distribute storage
fileItem.write(new File(savePath + File.separator + fileItem.getName()));
//fileItem.delete(); // close resource
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. File download
client ->( Send a request to tell the server what file I want to download ) -> The server
What the server does :
Get the name of the file to download
Read the contents of the file to be downloaded
Tell the client what the returned data type is through the response header ( It is the same as the type to be downloaded )
Tell the client that the data received is for downloading ( Or use the response header to set )
Send the downloaded file content back to the client for downloading
This can also be used commons-io-1.4.jar Of IOUtils class :
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8"); // Prevent confusion code
resp.setCharacterEncoding("UTF-8");
//1. Get the file name and path name to download , And pass ServletContext Read read file
String downloadFileName = "head.jpg"; // We are dead here
ServletContext servletContext = getServletContext();
String savePath = servletContext.getRealPath("/WEB-INF/upload"); // The directory where the previously uploaded files are saved
String downloadPath = savePath + File.separator + downloadFileName;
//2. Tell the client what type to return
String downloadType = servletContext.getMimeType(downloadPath); // Get the type of file to download ( This is image/jpeg)
resp.setContentType(downloadType); // ( Just like the type to download )
//3. Tell the client that the data received is for download , Not directly displayed on the page
// Content-Disposition How to handle the received data ,attachment Indicates that the attachment is downloaded and used ,filename Indicates the name of the downloaded file
// filename Names can be different from local names , When there is Chinese, it will be garbled , because http Chinese is not supported when setting the protocol , Need to carry out url code
/resp.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
resp.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(downloadFileName, "UTF-8"));
InputStream resourceAsStream = servletContext.getResourceAsStream(downloadPath);
// getResourceAsStream() Incoming file path , Read the file !!!!!!!!!!!!!
// 4.commons-io-1.4.jar There is IOUtils We can use it directly , You don't have to be yourself read() write() 了
ServletOutputStream outputStream = resp.getOutputStream(); // Get the output stream of the response
IOUtils.copy(resourceAsStream, outputStream);
// Read the information from the input stream and copy it to the output stream , Output to the client , Pass in an input stream and an output stream ( Byte character stream is OK )
}
边栏推荐
- Hugo blog building tutorial
- kali局域网ARP欺骗(arpspoof)并监听(mitmproxy)局域内其它主机上网记录
- In 2021, the global revenue of chlorinated polyvinyl chloride (CPVC) was about $1809.9 million, and it is expected to reach $3691.5 million in 2028
- Rhca memoirs -- Introduction to cl280
- Cookie & session & kaptcha verification code
- 232-CH579M学习开发-以太网例程-TCP服务器(项目应用封装,局域网或广域网测试)
- Research Report on the overall scale, major manufacturers, major regions, products and applications of Electric Screwdrivers in the global market in 2022
- Research Report on current market situation and investment prospect of China's tobacco RFID industry 2022-2027
- Meituan won the first place in fewclue in the small sample learning list! Prompt learning+ self training practice
- leetcode:5270. 网格中的最小路径代价【简单层次dp】
猜你喜欢

leetcodeSQL:602. Friend application II: who has the most friends

In 2021, the global revenue of chlorinated polyvinyl chloride (CPVC) was about $1809.9 million, and it is expected to reach $3691.5 million in 2028

CVPR 2022 oral Dalian Institute of technology proposed SCI: a fast and powerful low light image enhancement method

How to modify the authorization of sina Weibo for other applications

A journey of database full SQL analysis and audit system performance optimization

Super heavy! Apache Hudi multimode index optimizes queries up to 30 times

RHCA回忆录---CL280介绍

The Bean Validation API is on the classpath but no implementation could be found

leetcode:6094. 公司命名【分组枚举 + 不能重复用set交集 + product笛卡儿积(repeat表示长度)】
![[today in history] June 12: the United States entered the era of digital television; Mozilla's original developer was born; 3com merges with American Robotics](/img/91/d7d6137b95f6348f71692164614340.png)
[today in history] June 12: the United States entered the era of digital television; Mozilla's original developer was born; 3com merges with American Robotics
随机推荐
OpenGL shadow implementation (soft shadow)
kali局域网ARP欺骗(arpspoof)并监听(mitmproxy)局域内其它主机上网记录
The solution of BiliBili video list name too long and incomplete display
What are the third-party software testing organizations in Shanghai that share knowledge about software validation testing?
Operational research optimization of meituan intelligent distribution system - Notes
leetcode:98. Count the number of subarrays whose score is less than k [double pointers + number of calculated subsets + de duplication]
Redis(三十二)-用Redis做分布式锁
Report on the development status of China's asset appraisal industry and suggestions for future strategic planning 2022-2027
[image denoising] image denoising based on regularization with matlab code
Go init initialization function
觀察網站的頁面
Leetcode 1049. Weight of the last stone II
In 2021, the global revenue of chlorinated polyvinyl chloride (CPVC) was about $1809.9 million, and it is expected to reach $3691.5 million in 2028
Six stone cognition: the apparent and potential speed of the brain
ISCC2022
收获满满的下午
io.seata.common.exception.FrameworkException: can not connect to services-server.
bilibili视频列表名字太长显示不全的解决方法
kali通过iptables实现端口转发功能
YOLOX网络结构详解