springboot图片上传与回显

一,文件配置

springboot图片上传与回显_第1张图片

server:
  port: 8080

spring:
  servlet:
    multipart:
      max-file-size: 128MB
      max-request-size: 128MB

二,前台界面

    2.1上传界面:

      

   
    javaex.upload({         type : "image",         url : "upload", // 请求路径         id : "upload", // 的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 data = new HashMap();
	
	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 getData() {
		return data;
	}
	public void setData(Map data) {
		this.data = data;
	}
}

     common:

        StorageProperties.java

        文件上传路径
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 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 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);

    }

}


子类:StorageFileNotFoundException.java

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();
		};
	}


四,效果展示
springboot图片上传与回显_第2张图片

springboot图片上传与回显_第3张图片

你可能感兴趣的:(springboot)