最近在做springboot項目的時候,需要上傳圖片並且提供URL給前端。廢話不多說,直接上代碼。
首先在application.yml配置中添加如下配置
###服務啓動端口號
server:
port: 8003
tomcat:
uri-encoding: UTF-8
###文件上傳
file:
###靜態資源對外暴露的訪問路徑
staticAccessPath: /api/file/**
###靜態資源實際存儲路徑
uploadFolder: F:/upload/mall/
uploadImage: image/
###項目名
servlet:
context-path:
###文件上傳
multipart:
enabled: true
max-file-size: 10mb
max-request-size: 10mb
###服務名稱(服務註冊到eureka名稱)
spring:
application:
name: test
mvc:
throw-exception-if-no-handler-found: true
static-path-pattern: /**
#靜態資源訪問
resources:
add-mappings: true
static-locations: classpath\:/META-INF/resources/,classpath\:/resources/,classpath\:/static/,classpath\:/public/,file\:${file.uploadFolder}${file.uploadImage}
http:
encoding:
force: true
charset: utf-8
enabled: true
然後新建一個類,繼承WebMvcConfigurerAdapter
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SuppressWarnings("deprecation")
@Configuration
public class UploadFilePathConfig extends WebMvcConfigurerAdapter{
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Value("${file.uploadImage}")
private String uploadImage;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:///" + uploadFolder + uploadImage);
super.addResourceHandlers(registry);
}
}
接着編寫controller類
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.snimay.entity.RetStruct;
import com.snimay.utils.FileUpload;
import com.snimay.utils.exception.MallException;
import com.snimay.utils.map.MapUtil;
@Controller
@RequestMapping("/fileupload/")
public class FileUploadController {
//獲取主機端口
@Value("${server.port}")
private String POST;
//靜態資源對外暴露的訪問路徑
@Value("${file.staticAccessPath}")
private String staticAccessPath;
//實際存儲路徑
@Value("${file.uploadFolder}")
private String uploadFolder;
//圖片
@Value("${file.uploadImage}")
private String uploadImage;
/**
* 獲取所有文件上傳前綴路徑
*
* @param file
* @param request
* @return
*/
@ResponseBody
@RequestMapping(value = "getSourceUrl.do", produces = "text/html;charset=UTF-8")
public String getPrefixPath(HttpServletRequest request, HttpServletResponse response) {
JSONObject resultObj = new JSONObject();
JSONObject dataObj = new JSONObject();
String fileUploadBackUrl = FileUpload.fileUploadBackUrl;
dataObj.put("sourceUrl", fileUploadBackUrl + FileUpload.sourceDir);
resultObj.put("code", 0);
resultObj.put("msg", "獲取所有路徑成功");
resultObj.put("data", dataObj);
return resultObj.toString();
}
/**
* Description: 上傳名片圖片
*
* @param request
* @param response
* @return
*/
@SuppressWarnings("unchecked")
@ResponseBody
@RequestMapping(value = "uploadBusinessCardImage.do", produces = "text/html;charset=UTF-8")
public String uploadBusinessCardImage(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
throw new MallException(-1,"上傳文件爲空");
}
String originalFilename = file.getOriginalFilename();
String result = FileUpload.FileUpLoadAndGetParam(file, POST, staticAccessPath, uploadFolder, uploadImage, originalFilename);
Map<String, Object> resultMap = JSONObject.parseObject(result.trim());
Map<String, Object> layeditMap = new HashMap<>();
if (resultMap.get("code").equals(0)) {
Map<String, Object> resultDataMap = (Map<String, Object>) resultMap.get("data");System.out.println(resultDataMap);
layeditMap.put("src", resultDataMap.get("http_url"));
layeditMap.put("title", resultDataMap.get("file_name"));
resultMap.put("data", layeditMap);
resultMap.remove("param");
result = resultMap.toString();
}
return result;
} catch (Exception e) {
return new RetStruct(-1, e.getMessage()).toString();
}
}
}
上傳文件的工具類,最後返回結果封裝爲json格式
public class FileUpload {
private static final Logger log = LoggerFactory.getLogger(FileUpload.class);
public static String FILES_TYPE;
public static String IMG_TYPE;
public static int UPLOAD_MAX_SIZE;
public static long UPLOAD_MAX_SIZE_BYTE;
private Map<String, String> params;
private Map<String, Object> mFilesUrlJSON = new HashMap<>();
private static long fileSize = 0;
private String errStr = "";
static {
InputStream is = null;
try {
Properties pro = new Properties();
is = FileUpload.class.getResourceAsStream("/config.properties");
pro.load(is);
FILES_TYPE = FileType.getAllName();
IMG_TYPE = ImgType.getAllName();
UPLOAD_MAX_SIZE = pro.getProperty("uploadMaxSize") == null ? 2
: Integer.parseInt(pro.getProperty("uploadMaxSize"));
UPLOAD_MAX_SIZE_BYTE = UPLOAD_MAX_SIZE * 1024 * 1024;
is.close();
} catch (IOException e) {
ILogUtil.info(e.getMessage());
if (is != null) {
try {
is.close();
} catch (IOException e1) {
ILogUtil.info("關閉流出錯.");
}
}
}
}
/**
* Description:
* @param file 文件對象
* @param POST 端口號
* @param staticAccessPath 對外顯示路徑
* @param uploadFolder 上傳文件夾的主路徑
* @param filePath 上傳文件的文件夾路徑
* @param originalFilename 原始文件名稱
* @return
*/
public static String FileUpLoadAndGetParam(MultipartFile file, String POST, String staticAccessPath,
String uploadFolder, String filePath, String originalFilename) {
FileUpload fu = new FileUpload();
if (!fu.writeFile(file, POST, staticAccessPath, uploadFolder, filePath, originalFilename)) {
return RetResponse(10, "寫文件失敗," + fu.getErrStr());
}
JSONObject obj = fu.getFilesUrlJson();
JSONObject json = new JSONObject();
json.put("code", 0);
json.put("msg", "上傳成功");
json.put("data", obj);
json.put("param", fu.getParamsJson());
return json.toString();
}
private boolean writeFile(MultipartFile file, String POST, String staticAccessPath,
String uploadFolder,String filePath, String originalFilename) {
fileSize = file.getSize();
File fileExists = new File(uploadFolder + filePath);
try {
if (!fileExists.exists()) {
fileExists.mkdirs();
}
} catch (Exception e) {
ILogUtil.info(e.getMessage());
return false;
}
String oldFileName = originalFilename;
if (!checkFile(oldFileName, FILES_TYPE)) {
errStr = "校驗文件類型失敗,系統支持格式:" + FILES_TYPE;
ILogUtil.info("校驗文件類型失敗");
return false;
}
// 不是所有的上傳文件都有擴展名,需要允許上傳的文件沒有擴展名
String suffix = "";
int index = oldFileName.lastIndexOf(".");
if (index != -1) {
suffix = oldFileName.substring(index);
}
// 生成隨機名稱
String fileName = UUIDUtils.getUUID(16) + suffix;
mFilesUrlJSON.put("http_url", saveUploadFileVirtualUrl(POST, staticAccessPath) + fileName);
mFilesUrlJSON.put("file_name", fileName);
mFilesUrlJSON.put("server_url", saveUploadFileVirtualUrl(POST, staticAccessPath));
mFilesUrlJSON.put("path", "/" + filePath + fileName);// 存儲的目錄
mFilesUrlJSON.put("file_size", fileSize);
mFilesUrlJSON.put("suffix", suffix);
mFilesUrlJSON.put("old_file_name", oldFileName);
File newFile = new File(uploadFolder + filePath, fileName);
try {
file.transferTo(newFile);
} catch (Exception e) {
errStr = e.getMessage();
ILogUtil.info(e.getMessage());
return false;
}
return true;
}
/**
* Description: 獲取服務器地址,拼接虛擬路徑
* @return
*/
private String saveUploadFileVirtualUrl(String POST, String staticAccessPath) {
//獲取本機IP
String host = null;
try {
host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
ILogUtil.error("get server host Exception e:", e);
}
String virtual_url = host + ":" + POST + staticAccessPath.substring(0, staticAccessPath.length()-2);
return virtual_url;
}
private boolean checkFile(String fileName, String filesType) {
// 獲取文件後綴
if (filesType == null) {
// 不校驗
return true;
}
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
if (filesType.contains(suffix.trim().toLowerCase())) {
return true;
}
return false;
}
private Object getParamsJson() {
return (JSONObject) JSONObject.toJSON(params);
}
private JSONObject getFilesUrlJson() {
return JSONObject.parseObject(JSON.toJSONString(mFilesUrlJSON));
}
private String getErrStr() {
return errStr;
}
public static String RetResponse(int code, String msg) {
JSONObject obj = new JSONObject();
obj.put("code", code);
obj.put("msg", msg);
return obj.toString();
}
}
最後是生成隨機數的工具類
import java.util.UUID;
public class UUIDUtils {
public static String getUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public static String getUUID(Integer len) {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
}
}
用postman進行測試