项目1总结其三(图片上传功能)

1、UploadService

java 复制代码
public interface UploadService {
    //上传图片
    String uploadImage(MultipartFile file, String type);
}

upload.location = D:/upload

java 复制代码
@Value("${upload.location}")
    private String uploadLocation;//文件上传路径

    @Override
    public String uploadImage(MultipartFile file, String type) {
        //1.创建目录
        File dir = new File(uploadLocation + "/images/" + type);
        if (!dir.exists()) {
            boolean b = dir.mkdirs();//级联创建目录
            if (!b) {
                throw new F1Exception("级联创建目录异常");
            }
        }
        //2.给上传的文件起名
        LocalDateTime now = LocalDateTime.now();
        String fileName = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Random random = new Random();
        int sid = random.nextInt(1000);//0~999
        fileName = fileName + "-" + sid;

        //3.拼扩展名
        String originalFileName = file.getOriginalFilename();//上传文件名
        //assert originalFileName != null;
        int idx = originalFileName.lastIndexOf(".");
        String ext = originalFileName.substring(idx);
        fileName = fileName + ext;

        //完整的文件名
        String fullName = dir.getAbsolutePath() + "/" + fileName;

        //要存储的目标文件
        File target = new File(fullName);

        //4.存储文件
        try {
            file.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException("保存文件失败");
        }

        //5.返回访问地址和存储地址
        return "/images/" + type + "/" + fileName;
    }


修正:图片中的回显操作并非通过interceptor,而是通过资源定位实现的

后记:这里的D:/upload完全可以用@Value注入

思路就是:

通过组件的action操作---后端api调用service操作---保存文件---前端回显访问baseUrl + /image/xxx这个链接 --- 后端通过资源定位,将该链接定位到存放资源的位置

相关推荐
北城笑笑2 小时前
Vue 109 ,从零搭建 Vue3 + Electron 工程:生态、安全桥接与打包选型( Vue + Electron )
前端·javascript·vue.js·安全·electron·vue
小李不困还能学2 小时前
VSCode_RemoteSSH_一直卡在下载服务器_解决教程
服务器·ide·vscode
杨凯凡3 小时前
Spring Boot 链路追踪实战:Micrometer、TraceId 与异步线程上下文传播
java·spring boot·后端
计算机毕设定制辅导-无忧学长4 小时前
《基于Spring Boot的迷游哈游戏综合服务平台的开发》
java·vue.js·spring boot·mysql·迷游哈游戏综合服务平台
梦想恒远18 小时前
Spring Boot + LangChain4j 统计 token 成本:ChatModelListener 实测与单价口径
spring boot·后端
howard20051 天前
Spring Boot 版新生报到可视化系统
spring boot·新生报到可视化系统
她的男孩1 天前
子表只读列界面能改,保存却报不允许编辑:Forge Admin 把字段权限落到子表列
spring boot·低代码·工作流引擎
杨凯凡1 天前
MySQL 死锁怎么排查?InnoDB 锁等待与 Spring Boot 整事务重试实战
数据库·spring boot·mysql
独隅1 天前
WebStorm macOS 安装部署与高效调优完全指南
ide·macos·webstorm
RuoyiOffice2 天前
SpringBoot+Vue3 凭证生命周期设计:审核、过账、冲销与反过账怎样保持账目一致
java·spring boot·事务·springboot3·财务系统·会计凭证·ruoyi office