sprijngBoot 2.x版本不需要添加依賴包,soringBoot以及集成好了
一: 上傳文件 controller接受層
@PostMapping(value = "/fileUpload")
public String fileUpload(@RequestParam(value = "file") MultipartFile file, ModelMap model, HttpServletRequest request) {
if (file.isEmpty()) {
System.out.println("文件為空空");
}
String fileName = updateFile(request, file);
model.put("fileName",fileName);
return "update";
}
/**
*上傳到服務器的方法
*/
private String updateFile(HttpServletRequest request,MultipartFile files) {
MultipartFile file = files;
if (!file.isEmpty()){
try {
// 保存的文件路徑(如果用的是Tomcat服務器,文件會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夾中
// )
String filePath = request.getSession().getServletContext()
.getRealPath("/")
+ "upload/" + file.getOriginalFilename();
File saveDir = new File(filePath);
if (!saveDir.getParentFile().exists()){
saveDir.getParentFile().mkdirs();
}
// 轉存文件 保存到服務器地址上,路徑在filePath
file.transferTo(saveDir);
/**請求圖片服務器 返回字符串
* */
//得到圖片全名
String originalFilename = file.getOriginalFilename();
int i1 = originalFilename.indexOf(".");
String suffix = "";
if (i1 != 0){
suffix = originalFilename.substring(i1+1);
}else {
suffix = "jpg";
}
// String fileId = fileService.uploadWithGroup(
// FileCopyUtils.copyToByteArray(saveDir), FastDfsGroup.PRI_FILE, suffix);
String absolutePath = saveDir.getAbsolutePath();
String canonicalPath = saveDir.getCanonicalPath();
System.out.println(absolutePath+"---"+canonicalPath);
//absolutePath是文件的絕對路徑,下面jsp中,預覽頭像時,需要回傳到getUserLogo 接口中
return absolutePath;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
二: jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/recruit/hr/fileUpload" method="post" enctype="multipart/form-data">
<label>上傳圖片</label>
<input type="file" name="file"/>
<input type="submit" value="上傳"/>
</form>
<p>圖片:</p>
<img src="/recruit/hr/getUserLogo?path=${fileName}" style="width: 73px;height: 73px"/>
</body>
</html>
三:頭像預覽接口
/**
* 獲取頭像
* */
@RequestMapping("/getUserLogo")
public void getUserLogo(HttpServletRequest request,
HttpServletResponse response, String path) {
response.setContentType("image/jpeg"); // 設置返回內容格式
File file = new File(path); // 括號里參數為文件圖片路徑
if (file.exists()) { // 如果文件存在
InputStream in;
try {
in = new FileInputStream(file);
OutputStream os = response.getOutputStream(); // 創建輸出流
byte[] b = new byte[1024];
while (in.read(b) != -1) {
os.write(b);
}
in.close();
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
