34.项目day16-17

 

 

 

 

 

 

 

 

 

 

 

 

2.6 文件上传入门案例

 

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {

    /**
     * 文件上传入门案例
     * URL: /file/upload
     * 参数名:  file  二进制字节信息
     * 返回值: SysResult(imageVO)
     * 步骤:
     *      1.获取文件名称
     *      2.指定具体上传路径
     *      3.拼接文件的全路径
     *      4.实现上传
     */
    @PostMapping("/upload")
    public SysResult upload(MultipartFile file) throws IOException {
        //1.获取文件名称
        String fileName = file.getOriginalFilename();
        //2.定义上传路径  绝对路径  注意/问题
        String fileDir = "D:/JT-SOFT/image";
        File dirFile = new File(fileDir);
        if(!dirFile.exists()){
            //如果文件不存在,则应该创建一个新的目录
            dirFile.mkdirs(); //多级目录创建
        }
        //3.指定文件上传的全路径 目录/文件名称
        //D:/JT-SOFT/image/abc.jpg  注意/问题
        String filePath = fileDir + "/" + fileName;
        //4.实现文件上传
        file.transferTo(new File(filePath));
        return SysResult.success();
    }
}

2.7.2 编辑YML配置

说明: 添加文件上传的根目录

server:
  port: 8091
  servlet:
    context-path: /
spring:
  datasource:
    #如果使用高版本的数据库则添加cj
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/jt?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root


#mybatis-plush配置
mybatis-plus:
  type-aliases-package: com.jt.pojo
  mapper-locations: classpath:/mappers/*.xml
  configuration:
    map-underscore-to-camel-case: true

logging:
  level:
    com.jt.mapper: debug

#标识图片上传的路径
file:
  #本地存储的根目录
  localDir: D:/JT-SOFT/image
  #网络访问虚拟路径
  urlPath: http://image.jt.com

 

2.7.4 编辑FileService 

@Service
public class FileServiceImpl implements FileService{

    @Value("${file.localDir}")
    private String localDir;    //获取磁盘路径
    @Value("${file.urlPath}")   //spel表达式
    private String urlPath;     //获取虚拟路径

    /**
     * 业务说明:
     *      1.是否为图片类型
     *      2.防止恶意程序  木马.exe.jpg
     *      3.分文件目录存储 hash date  yyyy/MM/dd
     *      4.重新设定文件名称UUID
     *      5.实现文件上传
     *      6.封装VO对象之后返回
     * @return
     */
    @Override
    public ImageVO upload(MultipartFile file) {
        //1.校验图片类型 jpg|png|gif  a.jpg A.JPG
        String fileName = file.getOriginalFilename();
        //将字符全部转化为小写之后校验
        fileName = fileName.toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }

        //2.恶意程序校验  通过宽度/高度进行判断
        //将文件强制转化为图片
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width == 0 || height == 0){
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            //如果有错,则直接报错返回.
            return null;
        }

        //3.分目录存储 将当前时间格式化   /yyyy/MM/dd/
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd/")
                        .format(new Date());
        String fileDir = localDir + dateDir;
        File dirFile = new File(fileDir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }

        //4.动态生成UUID   a.jpg
        String uuid = UUID.randomUUID().toString()
                        .replace("-", "");
        //获取文件后缀
        int index = fileName.lastIndexOf('.');
        String fileType = fileName.substring(index);
        String realFileName = uuid + fileType;

        //5.实现文件上传
        String realFilePath = fileDir + realFileName;
        try {
            file.transferTo(new File(realFilePath));

            //6.封装VO对象
            ImageVO imageVO = new ImageVO();
            //存储文件磁盘地址:
            imageVO.setVirtualPath(realFilePath);
            //指定文件名称
            imageVO.setFileName(realFileName);
            //设定网络访问地址
            //https://img14.360buyimg.com/n1/s5463359/1/a70500aeed589028.jpg
            //http://image.jt.com/2021/11/11/uuid.jpg
            String url = urlPath + dateDir + realFileName;
            imageVO.setUrlPath(url);
            return imageVO;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

太彧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值