FileUploadController.java 4.49 KB
package com.tiptimes.ctrl;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/files")
public class FileUploadController {



    @RequestMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile[] files) throws IOException {

        Properties props = new Properties();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("file.properties");
        props.load(inputStream);
        String UPLOAD_PATH = props.getProperty("UPLOAD_PATH");

        if (files == null || files.length == 0) {
            return "请选择文件上传";
        }
        Map<String,String> fileUrls = new HashMap<>();
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                // 获取原始文件名
                String originalFileName = file.getOriginalFilename();
                // 生成时间戳
                String timeStamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                // 在文件名中加入时间戳,确保文件名唯一
                String fileNameWithTimeStamp = timeStamp + "_" + originalFileName;
                // 确保文件目录存在
                File destDir = new File(UPLOAD_PATH);
                if (!destDir.exists()) {
                    destDir.mkdirs();
                }
                // 文件上传后保存的路径
                String destPath = UPLOAD_PATH + fileNameWithTimeStamp;

                try {
                    // 保存文件
                    file.transferTo(new File(destPath));

                    // 添加上传文件的路径,并进行URL编码
                    fileUrls.put(fileNameWithTimeStamp,destPath);

                } catch (IOException e) {
                    e.printStackTrace();
                    return "文件上传失败:" + e.getMessage();
                }
            }
        }
        return fileUrls;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public boolean deleteFile(String fileName) throws IOException {

        Properties props = new Properties();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("file.properties");
        props.load(inputStream);
        String UPLOAD_PATH = props.getProperty("UPLOAD_PATH");

        String filePathToDelete = UPLOAD_PATH + fileName;
        File fileToDelete = new File(filePathToDelete);
        if (fileToDelete.exists()) {
            try {
                return fileToDelete.delete();
            } catch (SecurityException e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) {
        try {

            Properties props = new Properties();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("file.properties");
            props.load(inputStream);
            String UPLOAD_PATH = props.getProperty("UPLOAD_PATH");

            String newName = "";
            int lastDotIndex = fileName.lastIndexOf(".");
            if (lastDotIndex != -1 && lastDotIndex < fileName.length() - 1) {
                newName =  UUID.randomUUID() + fileName.substring(lastDotIndex);
            }

            Path filePath = Paths.get(UPLOAD_PATH).resolve(fileName);
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() && resource.isReadable()) {
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + newName);
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(resource);
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
}