文件上傳是開發(fā)中十分常見的功能,在servlet3.0之前,實(shí)現(xiàn)文件上傳需要使用一些插件技術(shù),比如:
- commons-fileupload
- smartupload
但是在3.0之后servlet內(nèi)部集成文件上傳的技術(shù)(multipart),有關(guān)servlet3.0文件上傳的實(shí)現(xiàn)過程如下:
1、表單的提交方式必須設(shè)置為post
2、表單的enctype必須設(shè)置為multipart/form-data(使用二進(jìn)制流的方式提交數(shù)據(jù))
3、在servlet類中加上@MultipartConfig注解
包含四個(gè)可設(shè)置的參數(shù)分別為:
- fileSizeThreshold 內(nèi)存緩存的最大空間(當(dāng)上傳文件的字節(jié)數(shù)達(dá)到該值后使用臨時(shí)文件緩存)
- location 臨時(shí)文件的存儲目錄
- maxFileSize 允許上傳的單個(gè)文件的最大限制
- maxRequestSize 表單允許提交的總字節(jié)數(shù)
頁面端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!DOCTYPE html> < html > < head > < meta charset = "UTF-8" > < title >Insert title here</ title > </ head > < body > < form action = "upload3" method = "post" enctype = "multipart/form-data" > < input type = "text" name = "fname" placeholder = "請輸入文件名" /> < br /> < input type = "file" name = "myfile" multiple/> < button >上傳</ button > </ form > </ body > </ html > |
服務(wù)端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package com.softeem.servlet; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet ({ "/UploadServlet" , "/upload" }) @MultipartConfig ( //設(shè)置內(nèi)存緩存的最大空間(當(dāng)上傳文件的字節(jié)數(shù)達(dá)到該值后使用臨時(shí)文件緩存) fileSizeThreshold= 1024 * 1024 , //設(shè)置臨時(shí)文件的存儲目錄 location= "d:/temp" , //設(shè)置允許上傳的單個(gè)文件的最大限制 maxFileSize= 1024 * 1024 * 200 , //設(shè)置表單的最大允許提交的字節(jié)數(shù) maxRequestSize= 1024 * 1024 * 500 ) public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String basePath = "d:/myfileserver" ; Collection<Part> parts = request.getParts(); for (Part part:parts){ if (part.getSize() > 0 ){ String fname = part.getSubmittedFileName(); //隨機(jī)產(chǎn)生一個(gè)uuid作為文件名稱 String uuid = UUID.randomUUID().toString(); //獲取文件后綴 String suffix = fname.substring(fname.lastIndexOf( "." )); //組合uuid和文件后綴成為新的文件名稱 fname = uuid+suffix; part.write(basePath+File.separator+fname); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_35937045/article/details/100182972