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

SpringBoot跨域上传图片

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

SpringBoot跨域上传图片

前言:

   写项目时突然要跨域上传文件,之前一直是存入到本地文件夹中,但是在尝试了好几个办法后找到了一个办法.

在SpringBoot项目中的application.yml文件中设置如下参数:

spring: 
 servlet:
    multipart:
      enabled: true
      max-file-size: 30MB
      max-request-size: 30MB
file:
  upload:
    path=http://localhost:8000/upload/:

引入跨服器上传所需要的jar包坐标

 
            com.sun.jersey
            jersey-core
            1.18.1

  
            com.sun.jersey
            jersey-client
            1.18.1

Controller中:

@Value("${file.upload.path}")
 private String path;
@PostMapping(path = "/fileupload")
    public CommonResult fileupload(@RequestParam("file") MultipartFile  file, @RequestHeader("token")String token){
        CommonResult commonResult=null;
        //获取照片的名称
        String oldFileName=file.getOriginalFilename();
       //获取新的照片名称,防止照片重名
        String newFileName= StringUtil.newFileName(oldFileName);
        //从token中获取登录人Id
        DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);//从token中解析用户的数据
        Integer id = tokenInfo.getClaim("id").asInt();
        try {
            // 创建客户端的对象
            Client client = Client.create();
            // 和图片服务器进行连接
            WebResource webResource = client.resource(path + newFileName);
            webResource.put(file.getBytes());

            //保存图片与账号的关系
            Admin admin1=new Admin();
            admin1.setId(id);
            admin1.setNewFileName(newFileName);
            admin1.setOldFileName(oldFileName);
            adminService.updateAdminFile(admin1);
            commonResult=new CommonResult(200,"上传成功",admin1);
            
        } catch (IOException e) {
            e.printStackTrace();
            commonResult=new CommonResult(500,"服务器忙,请稍后重试",null);
        }
        return commonResult;
    }

vue代码块:

handleAvatarChange(file) {
			var _this=this;
		    this.imageUrl = URL.createObjectURL(file.raw);
			var formData = new FormData();
			formData.append("file", file.raw);
			this.$http.post("admin/fileupload",formData).then(function(resp){
              //上传成功后,更新头像,刷新页面		
			}) 
		     },

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

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

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