栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot+Vue图片上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot+Vue图片上传

使用七牛云进行图片上传: 1.工具类QiniuUtils:

依赖


            com.qiniu
            qiniu-java-sdk
            7.2.0
        
public class QiniuUtils {
   public static String accessKey = "***";
   public static String secretKey = "***";
   public static String bucket = "***";

    public static void upload2Qiniu(String filePath, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(filePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet =
                    new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //上传文件
    public static void upload2Qiniu(byte[] bytes, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet =
                    new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //删除文件
    public static void deleteFileFromQiniu(String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        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());
        }
    }
}

注意:

这个地方需要根据自己创建存储空间选择的区域进行选择。

 2.后端代码 3.controller:
@Api("七牛云图片上传")
@CrossOrigin
@RestController
@RequestMapping(value ="/edossservice/oss/file")
public class OssController {

    @Autowired
    private FileService fileService;

    @ApiOperation("图片上传")
    @PostMapping(value ="/uploadImage")
    public R uploadImage(
            @ApiParam(value = "文件",name = "file",required = true)
            @RequestParam("file") MultipartFile file
    ){
        return R.ok().data("url",fileService.upload(file));
    }
}

 应为使用的是SpringBoot+vue所以要设置@CrossOrigin注解,保证可以跨域成功。

service:
public interface FileService {

    
    String upload(MultipartFile file);
}

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile imgFile) {
        System.out.println("upload..befor");
        try {
            //获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf - 1);
            //使用UUID随机产生文件名称,防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);
            System.out.println("upload..after");

            //将图片名称存入redis中

            //图片上传成功
            return "自己的地址"+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            //图片上传失败
            return "";
        }
    }
}
 4.前端代码
     
      
        
          
        
      
 //上传封面成功调用的方法
    handleAvatarSuccess (res, file) {
      this.courseInfo.cover = res.data.url
    },
    //上传之前调用的方法
    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
    },

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/756624.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号