原文地址:https://blog.csdn.net/davidchong210/article/details/49756575html
本文主要解決移動或者pc端上傳圖片及生成預覽的問題
1.jQuery 生成base64編碼,前臺預覽
2.jsp 自定義上傳按鈕兩種方式的上傳 input file 和 input hidden
3.java後臺兩種方式的上傳操做 SpringMvc自身的上傳機制和Base64解碼上傳的操做java
jQuery代碼:spring
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
56
57
58
59
60
Jsp代碼app
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
java代碼dom
@RequestMapping("uploadImg")
public ModelAndView uploadImg(String[] baseFile, HttpServletRequest request) throws IllegalStateException, IOException{jsp
ModelAndView mav = new ModelAndView(); mav.setViewName("MyJsp"); mav.addObject("mes", "Success!!!"); /** * springMvc 上傳圖片 * 1.enctype屬性的屬性值設爲multipart/form-data。 * 2.input的type屬性的屬性值設爲file。 * 後臺就可使用multipartResolver獲取到前臺上傳的文件 */ /* CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); if(multipartResolver.isMultipart(request)){ MultipartHttpServletRequest multipertRequest = (MultipartHttpServletRequest)request; Iterator<String> iter = multipertRequest.getFileNames(); //上傳一張圖片時能夠直接使用這個 //MultipartFile file11 = multipertRequest.getFile("files"); //上傳多張圖片 while (iter.hasNext()) { MultipartFile file = multipertRequest.getFile((String)iter.next()); if(!file.isEmpty()){ String path = request.getSession().getServletContext().getRealPath("uploadImg"); String imageName = this.getImageName(); //File.separator路徑分隔符 File savefile = new File(path+File.separator+imageName); //file.transferTo將上傳的文件寫入指定位置 file.transferTo(savefile); } } }*/
/**
* Base64 上傳圖片
*/
String path = request.getSession().getServletContext().getRealPath("uploadImg");
Base64 base64 = new Base64();
String[] imageNames = new String[baseFile.length];
//file 爲前臺隱藏域裏面的字符串
if(baseFile!= null && baseFile.length!=0){
int index = 0;
for (String base64Str : baseFile) {
//base64 解碼
byte[] byteArray = base64.decode(base64Str);
// 調整異常數據
for (byte b : byteArray) {
if(b<0)
b+=256;
}
String imageName = this.getImageName();
try {
OutputStream out = new FileOutputStream(path+File.separator+imageName);
out.write(byteArray);
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println(imageNames[0]);
}
imageNames[index] = path+File.separator+imageName;
index ++ ;
}
}
System.out.println(imageNames[0]);post
return mav;
}this
/**編碼