FileUploadController.java 2.4 KB
Newer Older
Q
qinyingjie 已提交
1 2
package com.kwan.springbootkwan.controller;

Q
qinyingjie 已提交
3 4
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
Q
qinyingjie 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author : qinyingjie
 * @version : 2.2.0
 * @date : 2022/12/19 16:07
 */
24
@Api(value = "文件上传信息", tags = "FileUploadController")
Q
qinyingjie 已提交
25 26 27 28 29 30 31 32 33 34
@RestController
public class FileUploadController {

    /**
     * 单文件上传
     *
     * @param uploadFile
     * @param req
     * @return
     */
Q
qinyingjie 已提交
35
    @ApiOperation(value = "单个文件上传", notes = "单个文件上传")
Q
qinyingjie 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() +
                oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            //文件保存操作
            uploadFile.transferTo(new File(folder, newName));
            //生成上传文件的访问路径, 并将访问路径返回
            String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                    + "/uploadFile/" + format + newName;
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "文件上传失败";
    }


    /**
     * 多文件上传
     *
     * @param uploadFiles
     * @param req
     * @return
     */
Q
qinyingjie 已提交
69
    @ApiOperation(value = "批量上传", notes = "批量上传")
Q
qinyingjie 已提交
70 71 72 73 74 75 76
    @PostMapping("/uploadBatch")
    public String uploadBatch(@RequestPart("uploadFile") MultipartFile[] uploadFiles, HttpServletRequest req) {
        //遍历 uploadFiles 数组分别存储
        return "success";
    }

}