当前位置: 首页 > article >正文

springboot完成一个线上图片存放地址+实现前后端上传图片+回显

1.路径

注意路径

2.代码:(那个imagePath没什么用,懒的删了),注意你的本地文件夹要有图片,才可以在线上地址中打开查看

package com.xxx.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class ResourceConfigurerAdapter implements WebMvcConfigurer {
    @Value("${image.path}")
    private String imagePath;

    /**
     * 配置资源访问
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**")
                .addResourceLocations("file:D:/code/img/");  //表示线上的存放的图片的来源:是D盘code下的img(所以你要做的就是将图片上传到这个本地文件夹)
    }

}

3.然后访问就是:localhost:端口号/img/图片名称.图片后缀

4.后端上传图片到特定文件夹:
 

package com.xxx.common.controller;

import com.xxx.common.service.UserService;
import com.xxx.common.utils.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8888") // 允许来自前端服务器的跨域请求
public class FileUploadController {

    @Autowired
    private UserService userService;

    //图片上传的地址
    private static final String UPLOAD_DIR = "D:\\code\\img";

    @PostMapping("/upload")
    public ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }

        try {
            String originalFilename = file.getOriginalFilename();
            // 可以添加更多的文件名检查和清理逻辑
            // 注意:直接使用用户提供的文件名存在安全风险,应该添加必要的校验和清理
            String randomString = generateRandomString(8);
            System.out.println("Random String: " + randomString);

            File destinationFile = new File(UPLOAD_DIR, "TX_"+randomString+originalFilename);
            file.transferTo(destinationFile);

            // 返回文件名作为响应
            return ResponseEntity.ok().body(destinationFile.getName());
        } catch (IOException e) {
            return new ResponseEntity<>("无法保存文件", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("/updateAvatar")
    public ResponseEntity<?> updateAvatar(@RequestBody Map<String, Object> payload) {

        //拿到现在的avtar的值,使用userMapper去数据表查找是否有该值,有的话就覆盖,然后提示图片已存在图片更新成功,已覆盖之前文件;如果查找不到的话就提示“第一次存入该图片”

        Integer userId = (Integer) payload.get("userId");
        String avatarName = (String) payload.get("avatar");
        userService.updateAvatar(userId, avatarName);
        return ResponseEntity.ok().body("头像更新成功");
    }

    public static String generateRandomString(int length) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        Random random = new Random();
        StringBuilder result = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            result.append(uuid.charAt(random.nextInt(uuid.length())));
        }

        return result.toString().toUpperCase();
    }


}

5.前端上传图片调用上面的后端的接口

6.前端回显图片:avatar是我的数据表的字段(存的是图片名称.后缀)
 

7.数据表

补充:
或者直接写个方法获取URL也可以获取头像

 


http://www.kler.cn/a/227525.html

相关文章:

  • 【智慧工业】东胜物联定位与跟踪解决方案,为方案商提供蓝牙网关、信标等物联网智能硬件设备
  • redis存储对象的过期设置在实际项目中的运用案例展示
  • 小公司要不要做绩效考核?七大理由告诉你,不做不行
  • 使用Python将Excel数据导入Word并设置字体样式(成功)
  • python将.db数据库文件转成Excel文档
  • MATLAB矩阵的操作(第二部分)
  • 【安装指南】nodejs下载、安装与配置详细教程
  • 记录Git无法连接Github(443报错)的一种可能——代理问题
  • CCF-CSP 202312-3 树上搜索(Java、C++、Python)
  • 前端学习笔记 | HTML5+CSS3静态网页制作的技巧(持续更新)
  • Qt之漂亮的地球
  • K8s之configMap
  • 考研/计算机二级数据结构刷题之顺序表
  • 有向图查询所有环,非递归
  • 【Linux网络编程三】Udp套接字编程网络应用场景
  • 【Django-ninja】使用Django ninja 进行auth鉴权
  • 清华系2B模型杀出,性能吊打LLaMA-13B
  • 如何在linux下使用openssl自签https的ip证书配置nginx
  • 笔记:《NCT全国青少年编程能力等级测试教程Python语言编程二级》
  • 单臂路由实验(华为)