本文實(shí)例為大家分享了WebUploader實(shí)現(xiàn)圖片上傳的具體代碼,供大家參考,具體內(nèi)容如下
描述:springmvc 在jsp頁(yè)面實(shí)現(xiàn) WebUploader插件上傳圖片, 上傳到 oss阿里云存儲(chǔ)上。
預(yù)覽:
理解: 前端 WebUploader插件(這個(gè)得去看官網(wǎng))調(diào)起后臺(tái),后臺(tái) request 接收文件參數(shù),
重新拼裝圖片url,oss創(chuàng)建連接上傳圖片提交圖片,最后返回圖片絕對(duì)url和相對(duì)url給前端。
先實(shí)現(xiàn)前端:1.定義js 2.定義頁(yè)面
1
2
3
|
//導(dǎo)入 WebUploader插件js、css 樣式 < link rel = "stylesheet" type = "text/css" href = "${ctx}/css/plugins/webuploader/webuploader.css" /> < script type = "text/javascript" src = "${ctx}/js/plugins/webuploader/webuploader.js" ></ script > |
js定義
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
|
//使用WebUploader插件做圖片上傳 function InfoWebUploaderImg(id, folder, image, imageHidden, queueID, filename){ // 初始化Web Uploader var uploader = WebUploader.create({ // 選完文件后,是否自動(dòng)上傳。 auto: true , // swf文件路徑 下載js 里面有.swf文件 swf: '/js/plugins/webuploader/Uploader.swf' , // 文件接收服務(wù)端。后臺(tái)控制層 server: '/common/upload' , // 選擇文件的按鈕。可選。 // 內(nèi)部根據(jù)當(dāng)前運(yùn)行是創(chuàng)建,可能是input元素,也可能是flash. pick: id, // 只允許選擇圖片文件。 accept: { title: 'Images' , extensions: 'gif,jpg,jpeg,bmp,png' , mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png' , }, }); /** * 驗(yàn)證文件格式、數(shù)量以及文件大小 */ uploader.on( "error" , function (type) { if (type == "Q_TYPE_DENIED" ) { alert( "請(qǐng)上傳圖片格式文件" ); } else if (type == "F_EXCEED_SIZE" ) { alert( "文件大小不能超過(guò)8M" ); } }); // 文件上傳失敗,顯示上傳出錯(cuò)。 uploader.on( 'uploadError' , function ( file ) { alert( "上傳失敗,請(qǐng)重試!" ); }); // 文件上傳成功,給item添加成功class, 用樣式標(biāo)記上傳成功。data回調(diào)的js uploader.on( 'uploadSuccess' , function (file,data) { $(imageHidden).val( '/' + data.nname); $(image).attr( "src" , data.src); $(image).css( "margin-top" , "10px" ); $(image).show(); $(image).removeClass( "hide" ); }); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//jsp頁(yè)面 < div class = "center-block" > < div class = "btn-group col-sm-12" > < div class = "fl" > < div id = "fileInput" >選擇圖片</ div > < img src = "" class = "wd200 mt10" id = "image" width = "200" /> </ div > < span class = "help-block m-b-none" >圖片大小:510x294</ span > < input class = "form-control" id = "imageHidden" name = "cover" type = "text" /> </ div > </ div > //引用 js初始化插件 InfoWebUploaderImg("#fileInput", "spvideoimg", "#image", "input[name=cover]", "singleDiv"); |
java 后臺(tái)
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
|
//上傳圖片(阿里云) 控制層 @ResponseBody @RequestMapping (value = "/upload" , method = RequestMethod.POST) public String upload( @RequestParam (value = "f" , required = false , defaultValue = "" ) String f, String folder, MultipartHttpServletRequest request, HttpServletResponse response) { return commonService.upload(folder, f, request, response); } //業(yè)務(wù)處理 public String upload(String folder, String f, MultipartHttpServletRequest request, HttpServletResponse response) { log.info( "CommonService上傳圖片(騰訊云):newFilename11:" + f); JSONObject jsonObject = new JSONObject(); String result = "" ; try { Iterator<String> itr = request.getFileNames(); MultipartFile file = null ; String name = "" ; while (itr.hasNext()) { file = request.getFile(itr.next()); name = file.getOriginalFilename(); String newFilenameBase = UUID.randomUUID().toString().replace( "-" , "" ); String originalFileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf( "." )); String newFilename = newFilenameBase + originalFileExtension; if (!StringUtils.isBlank(f)) { if (f.startsWith( "," )) f.substring( 1 ); newFilename = (f.contains( "." ) ? f.substring( 0 , f.lastIndexOf( "." )) : f) + ".jpg" ; } newFilename = "img/" + newFilename; AliyunOssUtils.upLoadFile(newFilename,PropertyUtil.getValue( "folder" ),file); //TentunOssUtils.uploadImage(file, newFilename); /*if (PropertyUtil.getValue("pic_url").endsWith("/")) { jsonObject.put("src", PropertyUtil.getValue("pic_url") + newFilename); } else { jsonObject.put("src", PropertyUtil.getValue("pic_url") + "/" + newFilename); }*/ jsonObject.put( "src" ,CommonUtils.setImageVideoUrlSign(newFilename)); jsonObject.put( "oname" , name); jsonObject.put( "nname" , newFilename); //刪除暫存在root里的圖片 File tempFile = new File(name); if (tempFile != null && tempFile.exists()) { tempFile.delete(); } } } catch (Exception e) { log.error( "上傳圖片異常" , e); jsonObject.put( "e" , e.getMessage()); } result = jsonObject.toString(); return result; } |
工具類(lèi):
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
61
62
|
/** * 文件上傳 * @param filename * @param file */ public static void upLoadFile(String filename,String folder, MultipartFile file) { try { // Endpoint以杭州為例,其它Region請(qǐng)按實(shí)際情況填寫(xiě)。 String endpoint = UPLOAD_HOST; // 阿里云主賬號(hào)AccessKey擁有所有API的訪問(wèn)權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM賬號(hào)進(jìn)行API訪問(wèn)或日常運(yùn)維 String accessKeyId = ACCESS_KEY_ID; String accessKeySecret = ACCESS_KEY_SECRET; // 創(chuàng)建OSSClient實(shí)例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 創(chuàng)建PutObjectRequest對(duì)象。 PutObjectRequest putObjectRequest = new PutObjectRequest(folder, filename, multipartFileToFile(file)); // 如果需要上傳時(shí)設(shè)置存儲(chǔ)類(lèi)型與訪問(wèn)權(quán)限,請(qǐng)參考以下示例代碼。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 上傳文件。 ossClient.putObject(putObjectRequest); // 關(guān)閉OSSClient。 ossClient.shutdown(); } catch (Exception e) { e.printStackTrace(); } } public static String setImageVideoUrlSign(String cover) { if (cover.startsWith( "/" )) cover = cover.substring( 1 ); String host = PropertyUtil.getValue( "pic_url" ); if (!host.endsWith( "/" )) host = host + "/" ; if (cover.startsWith( "http" ) && cover.contains(host)) { cover = host + cover + "?" + TentunOssUtils.getSigne(cover.replace(host, "" )); } else if (!cover.startsWith( "http" )) { cover = host + cover + "?" + TentunOssUtils.getSigne(cover); } return cover; } public static String getSigne(String key) { if (!key.startsWith( "/" )) key = "/" + key; String sign = "" ; String secretId = SECRET_ID; String secretKey = SECRET_KEY; COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); COSSigner signer = new COSSigner(); // 設(shè)置過(guò)期時(shí)間為1個(gè)小時(shí) Date expiredTime = new Date(System.currentTimeMillis() + 3600L * 1000L); // 要簽名的 key, 生成的簽名只能用于對(duì)應(yīng)此 key 的下載 // String key = "/exampleobject"; sign = signer.buildAuthorizationStr(HttpMethodName.GET, key, cred, expiredTime); return sign; } |
xml包:
1
2
3
4
5
6
|
<!-- 阿里云oss --> < dependency > < groupId >com.aliyun.oss</ groupId > < artifactId >aliyun-sdk-oss</ artifactId > < version >3.8.0</ version > </ dependency > |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_36837143/article/details/114690098