如下所示的代码,是一个在springboot项目中使用MultipartFile进行文件上传的示例:
package com.springboot.web;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/test")
public class UploadController {
private String path = "d:/temp";
@PostMapping("/upload")
public ResponseEntity upload(MultipartFile file) {
Map<String,Object> res = new HashMap<>();
try {
File outFile = new File(path.concat(File.separator).concat(file.getOriginalFilename()));
file.transferTo(outFile);
res.put("url",outFile.getAbsolutePath());
res.put("code",200);
} catch (Exception e) {
e.printStackTrace();
res.put("msg","upload fail");
res.put("code",500);
}
return ResponseEntity.ok(res);
}
}
我们在前端页面上,进行配置上传的时候,可以使用这样的form:
<form action="/test/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="upload"/&g