Springboot上傳圖片並訪問
步驟
-
配置絕對路徑,並將這個絕對路徑添加到springboot靜態資源目錄中。
-
文件上傳使用絕對路徑保存。返回web相對路徑,前端加上域名和項目路徑,生成完整的路徑。
注意如果路徑不是絕對路徑,則transfer方法實現會自動加上默認基礎路徑。
webappfile:
#文件上傳目錄(注意Linux和Windows上的絕對路徑不同,不能通用。)
# uploadPath: E:/image/upload/
uploadPath: /root/sources${server.servlet.context-path}/image/upload/
spring:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/, file:${webappfile.uploadPath}
server:
port: 80
servlet:
context-path: /mozq
打印日志
webPath=account/img
webFilePath=account/img/Snipaste_2019-06-24_15-46-57.png
filePath=/root/sources/mozq/image/upload/account/img/Snipaste_2019-06-24_15-46-57.png
uploadReal,destFile=/root/sources/mozq/image/upload/account/img/Snipaste_2019-06-24_15-46-57.png
uploadReal,destFile.getParentFile=/root/sources/mozq/image/upload/account/img
Controller
package com.mozq.boot.upload01.demo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
@RestController
public class UploadController {
@Autowired
private FileService fileService;
@Value("${webappfile.uploadPath}")
private String uploadPath;
@RequestMapping("/uploadNew")
public String uploadNew(@RequestParam("img")MultipartFile imgFile, HttpServletRequest request) throws IOException {
String webPath = "account/img";
System.out.println("webPath=" + webPath);
String webFilePath = PathUtil.appendWebPath(webPath, imgFile.getOriginalFilename());
System.out.println("webFilePath=" + webFilePath);
String filePath = PathUtil.appendWebPath(uploadPath, webFilePath);
System.out.println("filePath=" + filePath);
Map<String, String> result = fileService.uploadReal(filePath, imgFile);
result.put("webUrl", webFilePath);
return JSONObject.toJSONString(result);
}
}
FileService
public Map<String, String> uploadReal(String fileName, MultipartFile file){
//處理后綴
HashMap<String, String> result = new HashMap<>();
//獲取物理路徑
File destFile = new File(fileName);
System.out.println("uploadReal,destFile=" + destFile.getAbsolutePath());
System.out.println("uploadReal,destFile.getParentFile=" + destFile.getParentFile().getAbsolutePath());
//目錄不存在
if(!destFile.getParentFile().exists()){
destFile.getParentFile().mkdirs();
}
//目錄存在是文件
if(destFile.getParentFile().isFile()){
result.put("flag", "fail");
result.put("message","父級路徑是文件而不是目錄");
return result;
}
//文件已經存在
/*if(destFile.exists()){
result.put("flag", "fail");
result.put("message","文件已經存在");
return result;
}*/
try {
file.transferTo(destFile);
result.put("flag", "success");
result.put("message","文件上傳成功");
} catch (IOException e) {
e.printStackTrace();
result.put("flag", "fail");
result.put("message","文件寫入本地發生異常");
}
return result;
}
PathUtil
package com.mozq.boot.upload01.demo;
import java.io.File;
public class PathUtil {
public static String appendPathSep(String src, String separator, String... addPaths){
StringBuilder result = new StringBuilder(src);
for (int i = 0; i < addPaths.length; i++) {
String temp = addPaths[i].startsWith(separator)? addPaths[i] : separator + addPaths[i];
if(result.toString().endsWith(separator)){
//含頭不含尾。
result.delete(result.length() - separator.length(), result.length());
}
result.append(temp);
}
return result.toString();
}
public static String appendWebPath(String src,String... addPaths){
return appendPathSep(src, "/", addPaths);
}
public static String appendPath(String src, String... addPaths){
return appendPathSep(src, File.separator, addPaths);
}
public static boolean startWith(String src, String[] sep){
for (String s : sep) {
if(src.startsWith(s)){
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(PathUtil.startWith("jie",new String[]{"/"}));
System.out.println(PathUtil.startWith("/jie",new String[]{"\\"}));
System.out.println(PathUtil.startWith("\\jie",new String[]{"\\","/"}));
// String s = PathUtil.appendPathSep("acount/", "/","/jie/chagn", "/xie/aaa/");
// System.out.println(s);
/*StringBuilder sb = new StringBuilder("mozq/account/img/");
sb.delete(sb.length() - 2 , sb.length() - 1);
System.out.println(sb.toString());*/
// StringBuilder sb = new StringBuilder("mozq/account/img/");
// sb.delete(-2, -3);//Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
//System.out.println(null + "123");
//StringBuilder stringBuilder = new StringBuilder(null);
//Exception in thread "main" java.lang.NullPointerException
}
}