Java上传文件保存到指定路径
上代码
@PostMapping("/file-upload")
@ApiOperation(value = "上传swagger.json", httpMethod = "POST")
public String fileUpload(@ApiParam(value = "swaggerJsonFile", required = true) @RequestParam(value = "swaggerJsonFile") MultipartFile freeMarkerFile) {
OutputStream os = null;
InputStream inputStream = null;
//保存文件的文件名
String fileName = "swagger.json";
try {
inputStream = freeMarkerFile.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流保存到本地文件
String path = "D:\resources\";//保存到指定的文件目录
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath()+ "/" + File.separator + fileName);
// 开始读取
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileName;
}
@P