FileUploadController.java 2.1 KB
Newer Older
Q
qinyingjie 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 69 70 71
package com.kwan.springbootkwan.controller;

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
 */
@RestController
public class FileUploadController {

    /**
     * 单文件上传
     *
     * @param uploadFile
     * @param req
     * @return
     */
    @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
     */
    @PostMapping("/uploadBatch")
    public String uploadBatch(@RequestPart("uploadFile") MultipartFile[] uploadFiles, HttpServletRequest req) {
        //遍历 uploadFiles 数组分别存储
        return "success";
    }

}