springboot实现上传文件接口(简单版)

使用springboot实现一个最简单版本的上传文件接口

java 复制代码
private String uploadPath = "C:/imageFiles";


@RequestMapping(value = "/upload", method = RequestMethod.POST)
    private Result upload( @RequestParam("modelName") String modelName,
                           @RequestParam("file") MultipartFile multipartFile) {
        try {            
            StrBuilder sb = new StrBuilder();
            sb = sb.append(uploadPath).append(modelName);
            FileUtil.mkdir(sb.toString());
            String newFileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
            sb = sb.append("/").append(newFileName);
            FileOutputStream fileOutputStream = new FileOutputStream(sb.toString());
            fileOutputStream.write(multipartFile.getBytes());
            fileOutputStream.close();
            return new Result().success("/" + modelName + "/" + newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传文件IO异常");
            return new Result().error("上传文件IO异常");
        }
    }

上传完成之后需要访问,可以使用springmvc静态资源代理(线上项目不推荐,建议使用nginx静态资源代理)

java 复制代码
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 本地资源映射
        registry.addResourceHandler("/images/**").addResourceLocations("file:" + "C:/imageFiles/");
    }
}

尝试请求一下

成功返回!

相关推荐
SadSunset1 分钟前
(37)全注解式开发AOP
java·spring
秃然想通3 分钟前
Java多态完全指南:深入理解“一个接口,多种实现”
java·开发语言
TT哇4 分钟前
Optional<T>
java·spring boot·java-ee
李拾叁的摸鱼日常11 分钟前
Java泛型基本用法与PECS原则详解
java·后端·面试
MediaTea19 分钟前
Python:实例 __dict__ 详解
java·linux·前端·数据库·python
个案命题36 分钟前
鸿蒙ArkUI组件通信专家:@Param装饰器的奇幻漂流
java·服务器·前端
CodeCraft Studio43 分钟前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建折线图
java·c#·excel·aspose.cells·excel图表·excel api库·excel折线图
子超兄1 小时前
Bean生命周期
java·spring
程序员阿鹏1 小时前
事务与 ACID 及失效场景
java·开发语言·数据库
程序员清风1 小时前
阿里二面:新生代垃圾回收为啥使用标记复制算法?
java·后端·面试