以下给出一种springboot获取并保存前端传递的文件的方式:
前端拟采取ajax
异步传输FormData
,后端拟采取用MultipartFile
类型接收并保存。
先附后端代码:
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;
import java.io.IOException;
@RestController
public class UpPic {
@PostMapping("/uppic")
String uppic(@RequestParam("data") MultipartFile file) {
//System.out.println("进入后台成功");
String pathName = "myURL";//想要存储文件的地址
String pname = file.getOriginalFilename();//获取文件名(包括后缀)
pathName += pname;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pathName);
fos.writ