1. 程式人生 > 其它 >springBoot中檔案上傳功能Api

springBoot中檔案上傳功能Api

springBoot中檔案上傳功能Api

01) 實現工具類FileUtil

package com.example.fei.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

//檔案上傳工具類
public class FileUtil {
    public static void uploadFile(byte[] file,String filePath,String fileName) throws IOException {
        File targetFile 
= new File(filePath); if (!targetFile.exists()) { // 建立目錄 targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); out.write(file); out.flush(); out.close(); } public static void uploadFile2(InputStream fileStream, String filePath, String fileName) throws
IOException { File targetFile = new File(filePath); if (!targetFile.exists()) { // 建立目錄 targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); //開始複製 int i = 0; byte[] bytes = new byte[1024]; while
((i = fileStream.read(bytes))!=-1) { out.write(bytes, 0, i); } out.close(); fileStream.close(); } // 採用MultipartFile的transfer() 實現上傳 public static void uploadFile3(MultipartFile uploadFile, String filePath, String fileName) throws IOException { File targetFile = new File(filePath + fileName); uploadFile.transferTo(targetFile); } }

02) 在 Controller 中寫方法

package com.example.fei.controller;

import com.example.fei.common.utils.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/file")
public class FileController {

    // 上傳檔案
    @PostMapping("upload")
    public void upload(@RequestParam("file") MultipartFile file) {

        // String contentType = file.getContentType(); // 獲取檔案型別
        String fileName = file.getOriginalFilename(); // 圖片名字
        String filePath  = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\";

        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            // TODO: 處理異常資訊
        }
    }
    // 上傳檔案2
    @PostMapping("upload2")
    public void upload2(@RequestParam("file") MultipartFile uploadFile) {

        String fileName = uploadFile.getOriginalFilename();
        String filePath  = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\";

        try {
            FileUtil.uploadFile2(uploadFile.getInputStream(), filePath, fileName);
        } catch (Exception e) {
            // TODO: 處理異常資訊
        }

    }

    // 上傳檔案3
    @PostMapping("upload3")
    public void upload3(@RequestParam("file") MultipartFile uploadFile) {

        String fileName = uploadFile.getOriginalFilename();
        String filePath  = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\";

        try {
            FileUtil.uploadFile3(uploadFile, filePath, fileName);
        } catch (Exception e) {
            // TODO: 處理異常資訊
        }

    }

    // 下載檔案
    @GetMapping("download")
    public void download() {
    }
}
View Code

03) postman 測試