springBoot -文件上传
springBoot -文件上传
文件上传
实现工具类FileUtil
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
| 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(); }
public static void uploadFile3(MultipartFile uploadFile, String filePath, String fileName) throws IOException { File targetFile = new File(filePath + fileName); uploadFile.transferTo(targetFile); }
}
|
在 Controller
中写方法
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
| 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 fileName = file.getOriginalFilename(); String filePath = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\";
try { FileUtil.uploadFile(file.getBytes(), filePath, fileName); } catch (Exception e) { } } @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) { }
}
@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) { }
}
@GetMapping("download") public void download() { } }
|
用postman
测试接口
1 2 3 4 5
| http://localhost:8080/api/file/upload http://localhost:8080/api/file/upload2 http://localhost:8080/api/file/upload3
post 方式选择form-data
|

文件下载
…loading
底部
xxx没有了