在很多項目中都會有一臺專門的文件服務器來保存文件的,這邊記錄下客戶端通過jersey上傳圖片到文件服務端的實現。
由於要在不同主機上上傳文件,所以不能直接通過流的方式來寫,需要通過webService來完成,jersey是基於Java的一個輕量級RESTful風格的Web Services框架,它讓客戶端文件上傳變得更簡單。
1. maven依賴
spring的一些包以及fileupload和io包這邊就不貼出來了。
1
2
3
4
5
|
< dependency > < groupId >com.sun.jersey</ groupId > < artifactId >jersey-client</ artifactId > < version >1.2</ version > </ dependency > |
2. 配置tomcat下的conf/web.xml文件
打開文件服務器下的此文件,然後搜索readonly這個單詞,可以看到這段註釋代碼:
1
2
3
|
<!--
readonly Is this context "read only", so HTTP --> <!--
commands like PUT and DELETE are --> <!--
rejected? [true] --> |
通過註釋可以看到默認情況下當我們進行put或者delete操作的時候,服務器是拒絕訪問的,所以想向服務器上傳文件必須將readonly屬性設置爲false。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< servlet > < servlet-name >default</ servlet-name > < servlet-class >org.apache.catalina.servlets.DefaultServlet</ servlet-class > <!--
添加,解決jersey上傳服務器403錯誤 --> < init-param > < param-name >readonly</ param-name > < param-value >false</ param-value > </ init-param > < init-param > < param-name >debug</ param-name > < param-value >0</ param-value > </ init-param > < init-param > < param-name >listings</ param-name > < param-value >false</ param-value > </ init-param > < load-on-startup >1</ load-on-startup > </ servlet > |
3. 在文件服務器上創建文件存儲目錄
在webapp下創建一個upload目錄,爲了防止找不到目錄,在空目錄下隨便添加一個文件。
4. controller代碼
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
54
55
|
@Controller @RequestMapping ( "/upload" ) public
class
UploadController extends
BaseController { @RequestMapping (value
= "/uploadPic" ,
method = RequestMethod.POST) @LoginCheck public
void
uploadPic(HttpServletRequest request, PrintWriter out, String lastRealPath)
throws
IOException { //
將當前上下文初始化給CommonsMultipartResolver CommonsMultipartResolver
resolver = new
CommonsMultipartResolver(request.getSession().getServletContext()); //
檢查form中是否有enctype="multipart/form-data" if
(resolver.isMultipart(request)) { //
強制轉化request MultipartHttpServletRequest
req = (MultipartHttpServletRequest) request; //
從表單獲取input名稱 Iterator<String>
iterable = req.getFileNames(); //
存在文件 if
(iterable.hasNext()) { String
inputName = iterable.next(); //
獲得文件 MultipartFile
mf = req.getFile(inputName); byte []
mfs = mf.getBytes(); //
定義文件名 String
fileName = new
SimpleDateFormat( "yyyyMMddHHmmssSSS" ).format( new
Date()); Random
random = new
Random(); for
( int
i = 0 ;
i < 3 ;
i++) { fileName
= fileName + random.nextInt( 10 ); } //
獲得後綴名 String
oriFileName = mf.getOriginalFilename(); String
suffix = oriFileName.substring(oriFileName.lastIndexOf( "." )); //
要上傳文件的絕對路徑 String
realPath = MallUtil.readProp( "upload_file_path" )
+ "/upload/"
+ fileName + suffix; String
relativePath = "/upload/"
+ fileName + suffix; //
由於我們要在不同主機上上傳文件,所以不能直接通過流的方式來寫,需要通過webService來完成,這邊藉助Jersey來完成 Client
client = Client.create(); //
判斷是不是第一次上傳,如果已經上傳過則刪除上一次上傳的文件 if
(StringUtils.isNotBlank(lastRealPath)) { WebResource
webService = client.resource(lastRealPath); webService.delete(); } WebResource
webService = client.resource(realPath); //
將文件傳到主機上 webService.put(mfs); //
將圖片信息返回給界面回顯 Map<String,
String> map = new
HashMap<String, String>(); map.put( "realPath" ,
realPath); map.put( "relativePath" ,
relativePath); //
{"relativePath":"/upload/20170215135233634679.png","realPath":"http://localhost:8088/mall-file/upload/20170215135233634679.png"} out.write(JsonUtil.jsonString(map)); } } } } |
5. 頁面代碼
需要回顯就需要通過ajax來實現圖片上傳,這裏使用的是jquery.form.js這個插件
jsp代碼:
1
2
3
4
5
6
7
8
|
<form
enctype= "multipart/form-data"
id= "form" >
<div> ![](${path}/mall/image/load_image.png) <input
type= "file"
id= "input-image"
name= "input-image"
onchange= "submitUpload()" > <input
id= "input-relative-path"
name= "imgs"
type= "hidden"
> <input
id= "input-last-path"
type= "hidden" > </div> </form> |
js代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
function
submitUpload() { var
option = { url:
path + "/upload/uploadPic.do" , type:
"post" , dataType:
"text" ,
//
返回值的數據類型 beforeSubmit:
function
(formData, jqForm, options) { var
imageValue = $( "#input-image" ).val(); imageValue
= $.trim(imageValue); return
(imageValue != "" );
//
沒有選擇圖片,則中斷上傳請求 }, success:
function
(responseText) { //
{"relativePath":"/upload/20170215135233634679.png","realPath":"http://localhost:8088/mall-file/upload/20170215135233634679.png"} var
jsonObj = $.parseJSON(responseText); $( "#image" ).attr( "src" ,
jsonObj.realPath); $( "#input-relative-path" ).val(jsonObj.relativePath); $( "#input-last-path" ).val(jsonObj.realPath); }, error:
function
() { alert( "系統錯誤" ); } };
$( "#form" ).ajaxSubmit(option); } |
6. 常見錯誤
403 則是conf/web.xml中沒有添加readonly爲false的配置
409 : com.sun.jersey.api.client.UniformInterfaceException:
PUT http://localhost:8888/mall-file/upload/20170115104302348740.jpg returned a response status of 409 Conflict
確保項目部署在8888端口下並啓動成功,確保項目中存在upload目錄。