SpringBoot接收前端的文件,存到服务端

 Controller层:

    @PostMapping("/uploadfile")
    public ResponseResult uploadFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseResult.failResult("文件不能为空");
        }
        // 这里new的是目录
        File dir = new File(FILE_UPLOAD_PATH);
        if (!dir.exists() && !dir.isDirectory()) {
            // 若不存在该目录,就创建一个
            dir.mkdirs();
        }
        // 根据随机码+时间设置文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String oldName = file.getOriginalFilename();
        // 获取后缀
        int index = oldName.lastIndexOf('.');
        String suffix = oldName.substring(index);
        String newName = UUID.randomUUID() + "-" + sdf.format(new Date()) + suffix;
        // 将文件保存至服务端的本地
        file.transferTo(new File(FILE_UPLOAD_PATH + newName));
        // 生成前端路径
        String forePortPath = ACCESS_UPLOAD_PATH + newName;
        ResponseResult result = ResponseResult.okResult();
        result.setData(forePortPath);
        return result;
    }

配置:

@Configuration
public class MyWebConfiguration extends WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 网页访问资源的路径
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:" + PathConstants.FILE_UPLOAD_PATH);
    }

}

常量值:

public interface PathConstants {
    String FILE_UPLOAD_PATH = "D:\\mall-uploadfiles\\";
    String ACCESS_UPLOAD_PATH = "http://localhost:8080/upload/";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值