服務(wù)器中的文件上傳下載是基本操作,圖片、用戶頭像的上傳下載、文件的傳輸和資源分享等已經(jīng)成為每個(gè)應(yīng)用必不可少的功能。在我的認(rèn)知中,服務(wù)器的文件存儲(chǔ)下載簡(jiǎn)單流程是這樣的:上傳文件->在數(shù)據(jù)庫中記錄該文件的相關(guān)信息(文件名、大小、路徑等)->提供文件列表->文件下載。
由于項(xiàng)目中只有App增量更新需要上傳和下載文件,那么這里就將文件的路徑固定。
上傳下載頁面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>文件上傳</title>
</head>
<body>
<p>單文件上傳</p>
<form action="upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit"/>
</form>
<hr/>
<p>文件下載</p>
<a href="download">下載最新安裝包</a>
<hr/>
<p>多文件上傳</p>
<form method="POST" enctype="multipart/form-data" action="batch">
<p>文件1:<input type="file" name="file"/></p>
<p>文件2:<input type="file" name="file"/></p>
<p><input type="submit" value="上傳"/></p>
</form>
</body>
</html>
上傳和下載控制器:
@RestController
public class FileController {
private static final Logger log = LoggerFactory.getLogger(FileController.class);
@Autowired
private VersionService versionService;
@RequestMapping(value = "/upload")
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return "文件為空";
}
//獲取文件名
String fileName = file.getOriginalFilename();
log.debug("上傳的文件名字:" + fileName);
//獲取文件的后綴名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.debug("文件的后綴名為:" + suffixName);
// 設(shè)置文件存儲(chǔ)路徑
String filePath = "/usr/local/download/";
String path = filePath + fileName;
File dest = new File(path);
// 檢測(cè)是否存在目錄
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夾
}
file.transferTo(dest);// 文件寫入
return "上傳成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失敗";
}
@PostMapping("/batch")
public String handleFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
String filePath = "/usr/local/download/";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(
new File(filePath + file.getOriginalFilename())));//設(shè)置文件路徑及名字
stream.write(bytes);// 寫入
stream.close();
} catch (Exception e) {
stream = null;
return "第 " + i + " 個(gè)文件上傳失敗 ==> "
+ e.getMessage();
}
} else {
return "第 " + i
+ " 個(gè)文件上傳失敗因?yàn)槲募榭?;
}
}
return "上傳成功";
}
@GetMapping("download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "app_new.apk";
if (fileName != null) {
//設(shè)置文件路徑
File file = new File("/usr/local/live/download/" + fileName);
if (file.exists()) {
response.setContentType("application/force-download"); //設(shè)置強(qiáng)制下載不打開
//設(shè)置文件名
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下載成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下載失敗";
}
}