当前位置:网站首页>File upload and expansion
File upload and expansion
2022-07-29 08:54:00 【Don't want to be a programmer】
<%-- Form upload file
get: Upload file size is limited
post: There is no limit to
--%>
<form action="" enctype="multipart/form-data" method="post">
Upload users :<input type="text" name="username"><br>
<p><input type="file"/></p>
<p><input type="file"/></p>
<p><input type="submit">|<input type="reset"> </p>
</form>
public class UploadFileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = "";
// Judge whether the uploaded file is a common form With file form
if (!ServletFileUpload.isMultipartContent(req)) {
return;// Terminate method run , This is an ordinary form , Go straight back to
}
// Create a save path for the uploaded file , It is suggested that WEB-INF route , Security , Users cannot directly access the uploaded file ;
try {
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");// Get the global context , Real address
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdir();// Create this directory
}
// cache . The temporary file
// If the temporary file exceeds the expected size , We'll put him in a temporary file , Delete automatically in a few days , Or remind the user to save as a permanent file
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tmpfile = new File(tmpPath);
if (!tmpfile.exists()) {
tmpfile.mkdir();// Create this temporary directory
}
// 1. establish DiskFileItemFactory object , Handle file upload path or size limit
DiskFileItemFactory factory = getDiskFileItemfactory(tmpfile);
// 2、 obtain ServletFileUpload
ServletFileUpload upload = getServletFileUpload(factory);
// 3、 Handling upload files
msg = uploadParseRequest(upload, req, uploadPath);
} catch (Exception e) {
e.printStackTrace();
}
req.setAttribute("msg", msg);
req.getRequestDispatcher("info.jsp").forward(req, resp);
}
// 1、 Handle uploaded files , Generally, you need to obtain... Through flow , We can use request.getInputStream(), Original ecological file upload stream access , Very troublesome
// But we all recommend using Apach File upload component to achieve ,common-fileupload, It depends on commons-io Components
// Set a buffer through this factory , When the uploaded file is larger than this buffer , Put him in a temporary file
private DiskFileItemFactory getDiskFileItemfactory(File tmpfile) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);// The cache size is 1M
factory.setRepository(tmpfile);// Temporary file storage directory , Need one File
return factory;
}
// 2、 obtain ServletFileUpload
private ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
@Override
// pBytesRead: The size of the file that has been read
// pContentLength: file size
public void update(long pBytesRead, long pContentLength, int PItems) {
System.out.println(" Total size :" + pContentLength + " Uploaded :" + pBytesRead);
}
});
// Deal with the mess
upload.setHeaderEncoding("UTF-8");
// Set the maximum value of a single file
upload.setFileSizeMax(1024 * 1024 * 10);
// Set the total size of files that can be uploaded
// 1Kb*1024=1M*10=10M
upload.setSizeMax(1024 * 1024 * 10);
return upload;
}
//3、 Handling upload files
private String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws IOException {
// 3、 Handle uploaded files
// Parse the front-end request , Encapsulate into a FileItem object , Need from ServletFileUpload Get in object
List<FileItem> fileItems = null;
String msg = "";
try {
fileItems = upload.parseRequest(req);
} catch (FileUploadException e) {
e.printStackTrace();
}
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
// getFileName Refers to the front-end form control name;
String name = fileItem.getFieldName();
String value = fileItem.getString("utf-8");
// ========================= Processing documents =========================
// Get the name of the file
String uploadFileName = fileItem.getName();
// The file name may be illegal
if (uploadFileName.trim().equals("") || uploadFileName == null) {
continue;
}
// Get the name of the uploaded file /images/girl/pao.png
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
// Get the suffix of the file
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
/* * If the file suffix fileName It's not what we need * Just directly return, Don't deal with , Tell the user that the file type is wrong * */
// have access to UUID( A unique universal code ), Make sure the file name is unique
// UUID.randomUUID(), The most taboo is to generate a unique general code ;
// Things in network transmission All need to be serialized
// POJO, Entity class , If you want to run on multiple computers , transmission ---> You need to serialize all the objects
// JNT = Java Native Interface
// implement Serializable: Tag interface ,JVM--->Java Stack Native Method Stack native--->C++
String uuidPath = UUID.randomUUID().toString();
// ===================== Storage address completed ======================
// Where to deposit ?uploadPath
// The path of the real existence of documents realPath
String realPath = uploadPath + "/" + uuidPath;
// Create a folder for each file
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
// ====================== Storage address completed =====================
// Get stream for file upload
InputStream inputStream = fileItem.getInputStream();
// Create an output stream
// realPath = Real folders
// Missing a file ; Add the name of the output file +"/"+uuidFileName
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
// Create a buffer
byte[] buffer = new byte[1024 * 1024];
// Judge whether the reading is completed
int len = 0;
// If it is greater than 0 It means that there are data
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
// Closed flow
fos.close();
inputStream.close();
msg = " File upload succeeded ";
fileItem.delete();// File upload succeeded , Clear temporary files
// File transfer complete
}
}
return msg;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
边栏推荐
- C language sorts n integers with pointers pointing to pointers
- What if official account does not support markdown format file preparation?
- BI data analysis practitioners learn financial knowledge from scratch? What introductory books are recommended
- Amazfit dial Kit
- Day15 (day16 extension): file contains vulnerability
- ML.NET相关资源整理
- 7.2-function-overloading
- Common query optimization technology of data Lake - "deepnova developer community"
- ICMP message analysis
- 6.3 references
猜你喜欢
用户身份标识与账号体系实践
Normal visualization
Error reporting when adding fields to sap se11 transparent table: structural changes at the field level (conversion table xxxxx)
Qpalette learning notes
2022 electrician (elementary) test question simulation test platform operation
Lesson 3 threejs panoramic preview room case
数学建模——微分方程
LeetCode力扣题目总结(题目编号:53、3、141、面试题022、剑指offer链表中环的入口节点、20、19、牛客NC1、103、1143、牛客127)
Is the sub database and sub table really suitable for your system? Talk about how to select sub databases, sub tables and newsql
Intel will gradually end the optane storage business and will not develop new products in the future
随机推荐
Rocky基础之编译安装apache
不同数据库相同字段查不重复数据
Search and recall classic questions (eight queens)
User identity identification and account system practice
MySQL statement mind map
MFC integration QT verification and problem handling
Day15 (day16 extension): file contains vulnerability
Opencv cvcircle function
Collation of ml.net related resources
Leetcode deduction topic summary (topic No.: 53, 3, 141, interview question 022, the entry node of the link in the sword finger offer chain, 20, 19, Niuke NC1, 103, 1143, Niuke 127)
[C language] DataGridView binding data
Memory leaks and common solutions
Excellent Allegro skill recommendation
Amazfit dial Kit
Osgsimplegl3 example analysis
Component transfer participation lifecycle
How does xjson implement four operations?
AI application lesson 1: C language Alipay face brushing login
多重背包,朴素及其二进制优化
状态压缩dp