本文實例為大家分享了Spring Boot圖片上傳的具體代碼,供大家參考,具體內容如下
package com.clou.inteface.domain.web.user;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上傳
* @author Fly
*
*/
@RestController
public class FileUpload {
/**
* 用戶管理 -> 業務層
*/
@Autowired
private SUserService sUserService;
/**
* 文件上傳根目錄(在Spring的application.yml的配置文件中配置):<br>
* web:
* upload-path: (jar包所在目錄)/resources/static/
*/
@Value("${web.upload-path}")
private String webUploadPath;
/**
* ResultVo是一個對象,包含:
* private int errorCode;
* private String errorMsg;
* private Integer total;
* private Object data;
*/
/**
* 基於用戶標識的頭像上傳
* @param file 圖片
* @param userId 用戶標識
* @return
*/
@PostMapping(value = "/fileUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResultVo fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("userId") Integer userId) {
ResultVo resultVo = new ResultVo();
if (!file.isEmpty()) {
if (file.getContentType().contains("image")) {
try {
String temp = "images" + File.separator + "upload" + File.separator;
// 獲取圖片的文件名
String fileName = file.getOriginalFilename();
// 獲取圖片的擴展名
String extensionName = StringUtils.substringAfter(fileName, ".");
// 新的圖片文件名 = 獲取時間戳+"."圖片擴展名
String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
// 數據庫保存的目錄
String datdDirectory = temp.concat(String.valueOf(userId)).concat(File.separator);
// 文件路徑
String filePath = webUploadPath.concat(datdDirectory);
File dest = new File(filePath, newFileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// 判斷是否有舊頭像,如果有就先刪除舊頭像,再上傳
SUser userInfo = sUserService.findUserInfo(userId.toString());
if (StringUtils.isNotBlank(userInfo.getUserHead())) {
String oldFilePath = webUploadPath.concat(userInfo.getUserHead());
File oldFile = new File(oldFilePath);
if (oldFile.exists()) {
oldFile.delete();
}
}
// 上傳到指定目錄
file.transferTo(dest);
// 將圖片流轉換進行BASE64加碼
//BASE64Encoder encoder = new BASE64Encoder();
//String data = encoder.encode(file.getBytes());
// 將反斜槓轉換為正斜槓
String data = datdDirectory.replaceAll("\\\\", "/") + newFileName;
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("file", data);
resultVo.setData(resultMap);
resultVo.setError(1, "上傳成功!");
} catch (IOException e) {
resultVo.setError(0, "上傳失敗!");
}
} else {
resultVo.setError(0, "上傳的文件不是圖片類型,請重新上傳!");
}
return resultVo;
} else {
resultVo.setError(0, "上傳失敗,請選擇要上傳的圖片!");
return resultVo;
}
}
}
以上代碼需配置SUserService,一個業務層接口;
一個ResultVo對象,屬性已給出;
一個基於Spring Boot的 .yml配置文件的配置。
訪問圖片的時候,需要配置.yml文件
spring:
#配置http訪問服務器圖片的路徑
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
然後基於服務的IP與端口,http//IP:port/resources/static/圖片路徑(圖片名)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。