本文实例为大家分享了WebUploader实现图片上传的具体代码,供大家参考,具体内容如下
描述:springmvc 在jsp页面实现 WebUploader插件上传图片, 上传到 oss阿里云存储上。
预览:
理解: 前端 WebUploader插件(这个得去看官网)调起后台,后台 request 接收文件参数,
重新拼装图片url,oss创建连接上传图片提交图片,最后返回图片绝对url和相对url给前端。
先实现前端:1.定义js 2.定义页面
1
2
3
|
//导入 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({ // 选完文件后,是否自动上传。 auto: true , // swf文件路径 下载js 里面有.swf文件 swf: '/js/plugins/webuploader/Uploader.swf' , // 文件接收服务端。后台控制层 server: '/common/upload' , // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick: id, // 只允许选择图片文件。 accept: { title: 'Images' , extensions: 'gif,jpg,jpeg,bmp,png' , mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png' , }, }); /** * 验证文件格式、数量以及文件大小 */ uploader.on( "error" , function (type) { if (type == "Q_TYPE_DENIED" ) { alert( "请上传图片格式文件" ); } else if (type == "F_EXCEED_SIZE" ) { alert( "文件大小不能超过8M" ); } }); // 文件上传失败,显示上传出错。 uploader.on( 'uploadError' , function ( file ) { alert( "上传失败,请重试!" ); }); // 文件上传成功,给item添加成功class, 用样式标记上传成功。data回调的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页面 < 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 后台
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); } //业务处理 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; } |
工具类:
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请按实际情况填写。 String endpoint = UPLOAD_HOST; // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维 String accessKeyId = ACCESS_KEY_ID; String accessKeySecret = ACCESS_KEY_SECRET; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(folder, filename, multipartFileToFile(file)); // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 上传文件。 ossClient.putObject(putObjectRequest); // 关闭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(); // 设置过期时间为1个小时 Date expiredTime = new Date(System.currentTimeMillis() + 3600L * 1000L); // 要签名的 key, 生成的签名只能用于对应此 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 > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_36837143/article/details/114690098