springboot圖片上傳與回顯
阿新 • • 發佈:2019-01-01
一,檔案配置
server:
port: 8080
spring:
servlet:
multipart:
max-file-size: 128MB
max-request-size: 128MB
二,前臺介面
2.1上傳介面:
<form > <div class="right"> <!--上傳按鈕--> <a href="javascript:;"> <!-- 圖片承載容器 --> <label id="container" for="upload" style="display: inline-block; width: 132px; height: 74px;"> <img th:if="${id} == null" th:src="@{/javaex/pc/images/default.png}" width="100%" height="100%" /> <img th:if="${id} != null" th:src="@{${articleInfo.cover}}" width="100%" height="100%" /> </label> <input type="file" class="hide" id="upload" accept="image/gif, image/jpeg, image/jpg, image/png" /> </a> <input type="hidden" id="cover" name="cover" value="" /> </div> </form> javaex.upload({ type : "image", url : "upload", // 請求路徑 id : "upload", // <input type="file" />的id param : "file", // 引數名稱,SSM中與MultipartFile的引數名保持一致 dataType : "url", // 返回的資料型別:base64 或 url callback : function(rtn) { // 後臺返回的資料 if (rtn.code == "000000") { var imgUrl = rtn.data.imgUrl; $("#container img").attr("src", imgUrl); $("#cover").val(imgUrl); } else { javaex.optTip({ content : rtn.msg, type : "error" }); } } });
三,後臺程式碼
entity:
package com.springboot.entity; import java.util.HashMap; import java.util.Map; import org.springframework.util.StringUtils; public class Result { // code 狀態碼: 成功:000000,失敗:999999 private String code; // 錯誤資訊 private String message; // 返回的資料(鏈式) private Map<String, Object> data = new HashMap<String, Object>(); public static Result success() { Result result = new Result(); result.setCode("000000"); result.setMessage("操作成功"); return result; } public static Result error(String string) { Result result = new Result(); result.setCode("999999"); if (StringUtils.isEmpty(string)) { result.setMessage("操作失敗"); } else { result.setMessage(string); } return result; } public Result add(String key, Object value) { this.getData().put(key, value); return this; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> data) { this.data = data; } }
common:
檔案上傳路徑
package com.springboot.common; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("storage") public class StorageProperties { /** * Folder location for storing files */ private String location = "src/main/resources/static/upload-dir"; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
controller:
package com.springboot.controller;
import java.io.IOException;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.springboot.exception.StorageFileNotFoundException;
import com.springboot.service.StorageService;
/**
*
* 檔案上傳服務控制器
*
* @author Fantasy
*
*
*
*/
@Controller
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
// 跳轉到上傳圖片的介面
@GetMapping("/upload")
public String showUploadPage(Model model) throws IOException {
return "uploadForm";
}
// 以POST方式獲得請求,圖片上傳成功後,以JSON格式將圖片返回,用於回顯
@PostMapping("/upload")
@ResponseBody
public Result handleFileUpload(@RequestParam("file") MultipartFile file) {
String imgUrl = "/upload-dir/" + file.getOriginalFilename();
storageService.store(file);
return Result.success().add("imgUrl", imgUrl);
}
}
service:
介面:StorageService.java
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
實現介面類:FileSystemStorageService.java
package com.springboot.service.impl;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.common.StorageProperties;
import com.springboot.exception.StorageException;
import com.springboot.exception.StorageFileNotFoundException;
import com.springboot.service.StorageService;
@Service
public class FileSystemStorageService implements StorageService {
// 檔案儲存路徑
private final Path rootLocation;
@Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
}
@Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new StorageException("File is empty: " + filename);
}
if (filename.contains("..")) {
// 檔案路徑安全校驗
throw new StorageException(
"不能將檔案儲存到相對目錄路徑中: "
+ filename);
}
// 將上傳的檔案儲存到指定位置
Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e) {
throw new StorageException("上傳檔案失敗 " + filename, e);
}
}
/**
*
* 載入所有的檔案路徑
*
*/
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
}
catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename) {
return rootLocation.resolve(filename);
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
}
else {
throw new StorageFileNotFoundException(
"Could not read file: " + filename);
}
}
catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
@Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
@Override
public void init() {
try {
Files.createDirectories(rootLocation);
}
catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
exception:
父類:StorageException.java
package com.springboot.exception;
public class StorageException extends RuntimeException {
private static final long serialVersionUID = 2430191988074222554L;
public StorageException(String message) {
super(message);
}
public StorageException(String message, Throwable cause) {
super(message, cause);
}
}
子類:
package com.springboot.exception;
public class StorageFileNotFoundException extends StorageException {
private static final long serialVersionUID = -7119518537629449580L;
public StorageFileNotFoundException(String message) {
super(message);
}
public StorageFileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
主配置類:在Application中添加註解和bean元件
@EnableConfigurationProperties(StorageProperties.class)
//每次重新整理都初始化
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
// storageService.deleteAll();
// storageService.init();
};
}