springboot图片上传到服务器与通过链接查看(Windows本地也可以)

首先为演示方便,我这里已本地虚拟机代替服务器

上才艺, 首先是静态资源映射

(其实只需要实现WebMvcConfigurer就行,之所以选择继承WebMvcConfigurationSupport是为了后续方便接入swagger-ui)

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 静态资源映射
        registry.addResourceHandler("/img/**")     // 映射路径, 其中的img可以随便改
                .addResourceLocations("file:/root/opt/img/secKill/");  // 服务器中存放图片的路径
    }

}

若是本地路径,例如将图片放在D盘下,只需要修改为:

"file:D:/root/opt/img/secKill/"

然后就是接口了(Controller层),其中JsonResult是工具类,若不需要换成String即可

@PostMapping(value = "/userHead")
@ApiOperation(value = "用户头像上传")
// id需要是唯一的,否则会重名覆盖
public JsonResult<String> userHead(@RequestPart("file") MultipartFile file, Long id){
        // 获取上传的文件名
        String fileName = file.getOriginalFilename();   
        
        // 获得文件后缀名例如.png
        String lastName = fileName.substring(fileName.lastIndexOf("."));   
        
        // 生成新的文件名
        String newFileName = Id + lastName; 
        
        // 将文件路径与新的文件名拼接起来, 这是在静态资源中配置的路径
        File newPath = new File("/root/opt/img/secKill/",newFileName);

        // 判断文件夹是否存在若不存在则逐级创建
        if (!newPath.exists()) {
            newPath.mkdirs();
        }

        try {
            // 上传文件
            file.transferTo(newPath);
            // 将服务器
            // ip地址 http://192.168.73.140
            // 端口号 :8787
            // 静态资源的映射路径 /img/
            // 文件名 newFileName 
            // 进行拼接,并保存至数据库中
            if (userUpdateSelfInfoService.updateUserHeadByUserId("http://192.168.73.140:8787/img/" + newFileName ,userId)==1){
                return new JsonResult<>("图片已保存");
            }
            return new JsonResult<>("保存失败","410","预期外的错误");
        } catch (IOException e) {
            e.printStackTrace();
            return new JsonResult<>("保存失败","410","预期外的错误");
        }

}

    

其实看到这里,你就应该明白怎么做了,但是做戏做全套

JsonResult工具类

package com.SecKill.utils;
/**
 * @Description: 返回值封装工具类
 * @Author: 新写的旧代码
 * @CreateTime: 2022/4/11
 */
public class JsonResult<T>{

    private T data;
    private String code;
    private String msg;
    private String status;

    public JsonResult(T data) {
        this.data = data;
        this.code = "200";
        this.status = "success";
        this.msg = "success";
    }

    public JsonResult(T data, String code, String msg) {
        this.data = data;
        this.code = code;
        this.status = "fail";
        this.msg = msg;
    }

    public JsonResult(T data, String code, String msg, String status) {
        this.data = data;
        this.code = code;
        this.status = status;
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getStatus(){
        return status;
    }

    public void setStatus(String status){
        this.status = status;
    }

}

Service层

public interface UserUpdateSelfInfoService {
    int updateUserHeadByUserId(String userHead, Long userId);
}

ServiceImpl

package com.SecKill.service.impl;

import com.SecKill.mapper.UserUpdateSelfInfoMapper;
import com.SecKill.pojo.UserTable;
import com.SecKill.service.UserUpdateSelfInfoService;
import com.SecKill.vo.UpdatePassWordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @Author: 新写的旧代码
 * @Description: 针对表【user_table】的数据库操作Service实现
 * @CreateTime: 2022/4/14
 */
@Service
public class UserUpdateSelfInfoServiceImpl implements UserUpdateSelfInfoService {
    @Autowired
    private UserUpdateSelfInfoMapper userUpdateSelfInfoMapper;

    @Override
    public int updateUserHeadByUserId(String userHead, Long userId) {
        return userUpdateSelfInfoMapper.updateUserHeadByUserId(userHead, userId);
    }

}

Mapper层,我这里使用的是mybatis

package com.SecKill.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;

import com.SecKill.pojo.UserTable;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * @Author: 新写的旧代码
 * @Description: 针对表【user_table】的数据库操作Mapper
 * @CreateTime: 2022/4/14
 */

@Mapper
@Repository
public interface UserUpdateSelfInfoMapper extends BaseMapper<UserTable> {

    int updateUserHeadByUserId(@Param("userHead") String userHead, @Param("userId") Long userId);
}

sql语句

<update id="updateUserHeadByUserId">
        update user_table
        set user_head = #{userHead,jdbcType=VARCHAR}
        where user_id = #{userId,jdbcType=NUMERIC}
</update>

核心配置文件中关于文件上传的配置, 此配置的上一级是  -->   spring: 

servlet:
    multipart:
      # 设置单次请求的文件的总大小
      max-request-size: 100MB
      # 设置单个文件的大小,
      max-file-size: 10MB

图片获取:

图片保存至数据库后,直接使用即可

例: 

此时图片以链接形式存放于数据库中

复制链接到浏览器中查看

  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值