SpringBoot跨域上传图片

本文介绍了在SpringBoot项目中解决跨域问题并实现图片上传的方法。通过配置application.yml文件和引入相关依赖,结合Controller代码及Vue前端,成功实现了跨域文件上传的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:

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

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

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

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

 <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.18.1</version>
</dependency>
  <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.18.1</version>
</dependency>

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){
              //上传成功后,更新头像,刷新页面		
			}) 
		     },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值