@RequestMapping("/upload")
@ResponseBody
public WangEditorResult upload(HttpServletRequest request, MultipartFile file) throws IOException {
    // 创建文件夹,存放上传文件
    // 1.设置上传文件夹的真实路径
    String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/upload/img/product/small/";
    // 定义相对路径
    String relativePath = "src/main/resources/static/upload/img/product/small";

    // 创建路径对象并检查目录是否存在
    Path pathWrite = Paths.get(relativePath);
    if (!Files.exists(pathWrite)) {
        Files.createDirectories(pathWrite);
    }
    // 2.判断该文件夹是否存在,如果不存在,新建文件夹
    File dir = new File(realPath);
    if (!dir.exists()){
        dir.mkdirs();
    }
    // 拿到上传文件名
    String filename = file.getOriginalFilename();
    filename = UUID.randomUUID()+filename;
    // 生成完整文件路径
    File fileWrite = new File(pathWrite.toString(), filename);

    // 创建空文件
    File newFile = new File(dir, filename);
    // 创建文件并写入字节
    try (FileOutputStream fos = new FileOutputStream(fileWrite)) {
        fos.write(file.getBytes());
    }
    // 将上传的文件写到空文件中
    file.transferTo(newFile);
    // 构造返回结果
    WangEditorResult wangEditorResult = new WangEditorResult();
    wangEditorResult.setErrno(0);
    String[] data = {"/upload/img/product/small/"+filename};
    wangEditorResult.setData(data);
    return wangEditorResult;
}
这里如果实在不舒服的话,加一个io流可以使得上传的图片下次打开项目也能显示
相关课程:JAVA 全系列>第十阶段:百战旅游网项目>百战旅游网>后台产品管理_上传产品图片(2)

©2014-2023 百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备13018289号-12    营业执照    经营许可证:京B2-20212637