Controller
/**
* 文件上传
*/
@PostMapping(value = "/uploadFile")
@ResponseBody
public HttpResult uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
sysSubjectService.uploadSubjectMould(multipartFile);
return HttpResult.ok("上传完成");
}
Service
@Override
public Boolean uploadSubjectMould(MultipartFile multipartFile) {
FileIOUtil fileIOUtil = new FileIOUtil();
Boolean flag = fileIOUtil.uploadFile(multipartFile);
return flag;
}
FileIOUtil
import org.apache.tomcat.util.http.fileupload.util.Streams;
public class FileIOUtil {
public Boolean uploadFile(MultipartFile multipartFile) {
//设置文件名以及路径
String fileName = new String(multipartFile.getOriginalFilename()
.substring(multipartFile.getOriginalFilename().indexOf(".")));
String filePath = "D:\file" + File.separator + fileName;
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
if (multipartFile != null) {
try {
//以原来的名称命名,覆盖掉旧的
Streams.copy(multipartFile.getInputStream(), new FileOutputStream(filePath), true);
//或者下面的
// Path path = Paths.get(storagePath);
//Files.write(path,multipartFile.getBytes());
} catch (IOException e) {
ExceptionUtils.getFullStackTrace(e);
}
}
} catch (Exception e) {
return false;
}
return true;
}
}