Spring boot 实现上传文件

前端

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>文件上传和下载</title>
    </head>
    <body>
        <form action='/file/upload' method='post' enctype='multipart/form-data'>
            <input type='file' name='file'>
            <button type='submit'>上传</button>
        </form>
    </body>
</html>

java controller层

package com.zhou.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class TiktokSecuidController1 {
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    public String fileupload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        String oldName = file.getOriginalFilename();
        //获取原始文件的后缀
        String extension = "." + FilenameUtils.getExtension(oldName);
        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
        //文件大小
        Long size = file.getSize();
        //文件的类型
        String fileType = file.getContentType();
        //生成日期格式的目录  接收到的文件放在static下面的files中
        String realpath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
        //在files中动态的创建文件夹
        String dateDirpath = realpath + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File datedir = new File(dateDirpath);
        if (!datedir.exists()) {
            datedir.mkdirs();
        }
        //处理文件上传
        System.out.println(datedir);
        file.transferTo(new File(datedir, newFileName));
        return "success";
    }
}

pom

<!-- 文件上传下载工具包 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值