檔案上傳/下載後臺程式碼

羡仟發表於2024-09-13

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**

  • 檔案上傳介面
    */
    @RestController
    @RequestMapping("/files")
    public class FileController {

    //檔案上傳路徑
    private static final String filePath = System.getProperty("user.dir") + "/file/";

    /**

    • 檔案上傳
      */
      @PostMapping("/upload")
      public Result upload(MultipartFile file){
      synchronized (FileController.class){
      String flag =System.currentTimeMillis()+"";
      String fileName = file.getOriginalFilename();
      try{
      if(!FileUtil.isDirectory(filePath)){
      FileUtil.mkdir(filePath);
      }
      //檔案儲存格式:時間戳-檔名
      FileUtil.writeBytes(file.getBytes(),filePath + flag + "-" + fileName);
      System.out.println(fileName +"--上傳成功");
      Thread.sleep(1L);
      } catch (IOException | InterruptedException e) {
      System.out.println(fileName + "--檔案上傳失敗");
      }
      return Result.success(flag);
      }
      }

    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response){
    if (!FileUtil.isDirectory(filePath)){
    FileUtil.mkdir(filePath);
    }
    OutputStream os;
    List fileNames = FileUtil.listFileNames(filePath);
    String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
    try {
    if (StrUtil.isNotEmpty(avatar)){
    response.addHeader("Content-Disposition","attachment;filename"+ URLEncoder.encode(avatar,"UTF-8"));
    response.setContentType("application/octet-stream");
    byte[] bytes = FileUtil.readBytes(filePath + avatar);
    os = response.getOutputStream();
    os.write(bytes);
    os.flush();
    os.close();
    }
    } catch (Exception e) {
    System.out.println("檔案下載失敗");
    }
    }
    }

相關文章