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/");
    }
}

尝试请求一下

成功返回!

相关推荐
侠客行031720 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪20 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚21 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎1 天前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Yvonne爱编码1 天前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚1 天前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂1 天前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang1 天前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
琹箐1 天前
最大堆和最小堆 实现思路
java·开发语言·算法
__WanG1 天前
JavaTuples 库分析
java