上传文件之 文件上传到项目本身的文件夹当中 非上传到服务器当中

上传文件到项目本身static当中 而不是上传的文件服务器上。
这种一般是很少的,但是也不排除使用这个。

首先我们看一下controller 处理,这里是通过对象进行接收,MultipartFile 文件接收,当然这里对象也可以换成Map。这里就是上传的项目static/upload 下面。如下图
在这里插入图片描述
上代码

   @ResponseBody
    @PostMapping("/vehicles")
    public Object insert(Vehicle vehicle, @RequestParam(value = "file", required = false) MultipartFile file) throws FileNotFoundException {
        if (file != null && !file.isEmpty()) {
            String toPath = ResourceUtils.getURL("classpath:").getPath() + "static/upload";
            String realPath = toPath.replace('/', '\\').substring(1, toPath.length());
            vehicle.setAttach(FileUtils.TransTo(file, realPath));
        }
        return getResult(vehicleService.insert(vehicle));
    }

上面的FileUtils.TransTo 运用到工具类 如下:

class FileUtils {

    public static String TransTo(MultipartFile multipartFile, String toPath) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            return "";
        }

        File file = new File(toPath);
        if (!file.exists()) {
            //不存在就创建一个路径
            file.mkdirs();
        }

        String filename = multipartFile.getOriginalFilename();
        //把文件名称设置成唯一值uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;
        //完成上传文件
        try {
            multipartFile.transferTo(new File(toPath, filename));
        } catch (Exception e) {
            return "";
        }

        String result = "../upload/" + filename;
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值