java接口保存文件到本地指定目录下.md
一、需求
通过接口将 file 保存到本地指定目录下
动动发财小手,关注 + 点赞 + 收藏不迷路。
二、后端代码
package com.web.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileOutputStream;
/**
* @Author: tinker
* @Date: 2022/02/18 10:25
*/
@Slf4j
@RestController
public class FileUploadController {
@PostMapping("/file/upload")
String fileUpload(@RequestParam("file") MultipartFile file) {
String path = "D:\\uploadDir\\";
// 获取文件名(包括后缀)
String fileName = file.getOriginalFilename();
try (FileOutputStream fos = new FileOutputStream(path + fileName)) {
fos.write(file.getBytes());
return "文件上传成功";
} catch (Exception e) {
log.error("file upload failed, fileName = {}", file.getOriginalFilename(), e);
}
return "文件上传失败";
}
}
三、postman模拟页面上传
step1:
POST 请求,url = localhost:8080/file/upload
step2:
点击Body,选择 form-data,key 为 file,之后点击 value 选择一个文件,文件名为 test.txt
step3:
点击上传,可以发现本地 uploadDir 目录下已经上传成功了