实现上传文件

工具类

package com.project.supplier.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;

@Component
public class UploadUtil {
    public static String upload(MultipartFile mf, String dirPath) {

        //得到上传文件的名称
        String fileName = mf.getOriginalFilename();
        //文件重命名,防止同名
        fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));

        try {
            //得到上传文件存放目录的真实路径
            URL url = Thread.currentThread().getContextClassLoader()
                    .getResources(dirPath).nextElement();
            String filePath = URLDecoder.decode(url.getFile(), "utf-8");

            //将上传文件的二进制数据写入指定的文件
            mf.transferTo(new File(filePath+"/"+fileName));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileName;
    }
}

Controller

package com.project.supplier.controller;

import com.project.common.result.ResponseResult;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
@Api("上传文件的控制器")
@ResponseResult
public class IndexController {

    @ResponseBody
    @PostMapping("/upload")
    public Object upload(@RequestParam(value = "file", required = false) MultipartFile file){
        String path = "d:/server/upload";
        // 获取上传图片的文件名
        String fileName = file.getOriginalFilename();
        // 截取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成新的文件名(时间 + 随机数 + 后缀名)
        String newFileName = System.currentTimeMillis() + "_" + String.valueOf(Math.random()).substring(2) + suffixName;
        File targetFile = new File(path, newFileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFileName;

    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值