WebUploader实现图片上传功能
本文实例为大家分享了WebUploader实现图片上传的具体代码,供大家参考,具体内容如下
描述:springmvc 在jsp页面实现 WebUploader插件上传图片, 上传到 oss阿里云存储上。
预览:
文章图片
理解: 前端 WebUploader插件(这个得去看官网)调起后台,后台 request 接收文件参数,
重新拼装图片url,oss创建连接上传图片提交图片,最后返回图片绝对url和相对url给前端。
先实现前端:1.定义js 2.定义页面
//导入 WebUploader插件js、css 样式
js定义
//使用WebUploader插件做图片上传function InfoWebUploaderImg(id, folder, image, imageHidden, queueID, filename){// 初始化Web Uploadervar 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"); }); }
//jsp页面选择图片
文章图片
图片大小:510x294 //引用 js初始化插件InfoWebUploaderImg("#fileInput", "spvideoimg", "#image", "input[name=cover]", "singleDiv");
java 后台
//上传图片(阿里云) 控制层@ResponseBody@RequestMapping(value = "https://www.it610.com/upload", method = RequestMethod.POST)public String upload(@RequestParam(value = "https://www.it610.com/article/f", required = false, defaultValuehttps://www.it610.com/article/= "") 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 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; }
工具类:
/*** 文件上传* @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 = https://www.it610.com/article/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包:
com.aliyun.oss aliyun-sdk-oss3.8.0
【WebUploader实现图片上传功能】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。