1前端 页面
<el-row> <el-col :span="24"> <el-form-item label="上传图片"> <el-upload class="avatar-uploader" :action="backend_url+'/setmeal/upload.do'" :auto-upload="autoUpload" name="imgFile" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-form-item> </el-col> </el-row>
methods: { //图片上传完成后自动执行 handleAvatarSuccess(response) { this.imageUrl = response.data; this.$message({ message: response.message, type: response.flag ? 'success' : 'error' }); //设置模型数据(图片名称),后续提交ajax请求时会提交到后台最终保存到数据库 this.formData.img = response.data; }, //上传图片之前执行 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; },
}
2控制器
@RequestMapping("/upload") public Result upload(@RequestParam("imgFile") MultipartFile imgFile) { try { //获取原图片文件名 String fileName = imgFile.getOriginalFilename(); //文件名的基础上,在前面加入UUID,防止文件重名 String saveUploadNane = UUID.randomUUID().toString().replace("-", "") + "_" + fileName; //使用七牛工具类,完成图片上传 QiniuUtils.upload2QiNiu(imgFile.getBytes(), saveUploadNane); //把访问路径返回给客户端 String file_url = QiniuUtils.qiniu_img_url_pre + saveUploadNane; //把全路径返回给客户端 return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS, file_url); } catch (IOException e) { e.printStackTrace(); return new Result(false, MessageConst.PIC_UPLOAD_FAIL); } }
3工具类
package com.itheima.health.utils; import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.BucketManager; import com.qiniu.storage.Configuration; import com.qiniu.storage.Region; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.UUID; /** * @author :Mr.zhang * @date :Created in 2020/2/10 16:12 * @description:文件上传删除工具类 */ public class QiniuUtils { //...生成上传凭证,然后准备上传 public static String qiniu_img_url_pre = "http://q5h71deip.bkt.clouddn.com/"; private static String accessKey = "J8QtoadsadlaWLkx_R7jiLOKLkLxt-fuyzsGEe3Rm2q"; private static String secretKey = "AWqM8ZfdasdasdsFAsRwkXp1Vdwv89oyFt9r2t"; private static String bucket = "zzx843081626"; /** * 文件上传 * @param uploadBytes 文件内容,字节数组 * @param uploadFileName 保存到服务器端的文件名 */ public static void upload2QiNiu(byte[] uploadBytes, String uploadFileName){ //构造一个带指定 Region 对象的配置类 Configuration cfg = new Configuration(Region.region1()); //...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); //默认不指定key的情况下,以文件内容的hash值作为文件名 String key = uploadFileName; Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(uploadBytes, key, upToken); //解析上传成功的结果 System.out.println(response.bodyString()); //访问路径 System.out.println(qiniu_img_url_pre + uploadFileName); } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { //ignore ex2.printStackTrace(); } } } /** * 删除文件 * @param filename 服务端文件名 */ public static void deleteFile2QiNiu(String filename){ //构造一个带指定 Region 对象的配置类 Configuration cfg = new Configuration(Region.region1()); String key = filename; Auth auth = Auth.create(accessKey, secretKey); BucketManager bucketManager = new BucketManager(auth, cfg); try { bucketManager.delete(bucket, key); } catch (QiniuException ex) { //如果遇到异常,说明删除失败 System.err.println(ex.code()); System.err.println(ex.response.toString()); } } public static void main(String[] args) throws IOException { // 获取文件地址 String localFilePath = "F:/学校/个人照片/001.jpg"; FileInputStream fileInputStream = new FileInputStream(localFilePath); byte[] data = new byte[1024 * 1024]; fileInputStream.read(data); String saveFileName = UUID.randomUUID().toString().replace("-", ""); QiniuUtils.upload2QiNiu(data, saveFileName); } }