servlet: multipart: max-file-size: 10MB max-request-size: 100MB # 上传文件的大小把控 可自定义大小
service层String upload(InputStream inputStream , String fileName);
@Overridepublic String upload(InputStream inputStream, String fileName) { //构造一个带指定 Region 对象的配置类 //Region.region2();代表华南地区 Configuration cfg = new Configuration(Region.region2()); //...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); //...生成上传凭证,然后准备上传 //AK和SK从七牛云个人中心秘钥管理查看 String accessKey = "your access key";String secretKey = "your secret key"; //bucket就是创建String bucket = "your bucket name"; //默认不指定key的情况下,以文件内容的hash值作为文件名 String key = fileName; String result = null; try { Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(inputStream, key, upToken,null,null); System.out.println(response); //解析上传成功的结果 if(response.statusCode==200){ //返回图片上传的路径地址 result = "http://www.sunpeizhi.top/"+fileName; } } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { //ignore } } } catch (Exception ex) { //ignore } return result;}
controller层@RequestMapping("/upload")//file跟前端的name值一样 public Object fileupload(MultipartFile file) throws IOException { System.out.println("---------files/upload---------"); String filename = file.getOriginalFilename(); String date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDateTime.now()); filename = date+System.currentTimeMillis()+filename.substring(filename.lastIndexOf(".")); String name = service.upload(file.getInputStream(), filename); System.out.println("name="+name); return Result.success(name,"上传成功"); }
前端vue//上传图片之前执行beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传套餐图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传套餐图片大小不能超过 2MB!'); } return isJPG && isLt2M;},//文件上传成功后的钩子,response为服务端返回的值,file为当前上传的文件封装成的js对象handleAvatarSuccess(response, file) { console.log(response); //为模型数据imageUrl赋值,用于页面图片预览 this.imageUrl = response.data; this.$message({ type: response.code == 0 ? 'success' : 'error', message: response.msg }); //设置模型数据(图片名称),后续提交ajax请求时会提交到后台最终保存到数据库 this.registerForm.images = response.data; this.form.images = response.data;},