Spring Boot上传图片与展示

1、配置相关限制参数:application.yml

upload: #文件上传配置
  localtion:  #配置默认文件保存位置
    windows: c:/Users/meatball/file/
    linux: /var/local/meatball/file/
  maxFileSize: 10240KB #单个文件最大KB/MB
  maxRequestSize: 102400KB   #设置总上传数据总大小

2、配置参数读取Bean:UploadProperties

/**
 * Project Name:meatball-core
 * File Name:MeatballProperties.java
 * Package Name:com.meatball.component
 * Date:2017年10月14日下午2:54:03
 * Copyright (c) 2017, zhang.xiangyu@foxmail.com All Rights Reserved.
*/
package com.meatball.component;

import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**   
 * @Title: MeatballProperties.java 
 * @Package com.meatball.component 
 * @Description: TODO(读取自定义配置参数) 
 * @author 張翔宇  
 * @date 2017年10月14日 下午2:54:03 
 * @version V1.0   
 */
@Component
@ConfigurationProperties("upload")
public class UploadProperties {
	// 获取存放位置
	private Map<String, String> localtion;
	
	// 单个文件大小
	private String maxFileSize;
	
	// 单次上传总文件大小
	private String maxRequestSize;
	
	public Map<String, String> getLocaltion() {
		return localtion;
	}

	public void setLocaltion(Map<String, String> localtion) {
		this.localtion = localtion;
	}

	public String getMaxFileSize() {
		return maxFileSize;
	}

	public void setMaxFileSize(String maxFileSize) {
		this.maxFileSize = maxFileSize;
	}

	public String getMaxRequestSize() {
		return maxRequestSize;
	}

	public void setMaxRequestSize(String maxRequestSize) {
		this.maxRequestSize = maxRequestSize;
	}

	public String getBasePath() {
		String location = "";
		String os = System.getProperty("os.name");
		if(os.toLowerCase().startsWith("win")) {
			location = this.getLocaltion().get("windows");
		} else {
			location = this.getLocaltion().get("linux");
		}
		return location;
	}
}

3、上传与展示

/** 
 * Project Name:meatball-admin 
 * File Name:FileUpload.java 
 * Package Name:com.meatball.component 
 * Date:2017年10月12日下午10:19:16 
 * Copyright (c) 2017, zhang.xiangyu@foxmail.com All Rights Reserved. 
 */  
package com.meatball.utils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.JSON;
import com.meatball.component.UploadProperties;
import com.meatball.utils.DateUtil;
import com.meatball.vo.FileUploadResponse;

/**   
 * @Title: FileUpload.java 
 * @Package com.meatball.component 
 * @Description: TODO(上传) 
 * @author 張翔宇  
 * @date 2017年10月12日 下午10:19:16 
 * @version V1.0   
 */
@Controller
public class FileUploadUtil {
	private Logger log = LoggerFactory.getLogger(FileUploadUtil.class);
	@Resource
	private ResourceLoader resourceLoader;
	@Resource
	private UploadProperties uploadProperties;
	/**
	 * @Title: upload 
	 * @Description: TODO(上传) 
	 * @param file
	 * @param request
	 * @return String    返回类型
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public List<FileUploadResponse> upload(@RequestParam("file") MultipartFile[]  files, HttpServletRequest request) {
		List<FileUploadResponse> list = new ArrayList<FileUploadResponse>();
		// 获取文件存放路径
		String basePath = uploadProperties.getBasePath();
		String location = DateUtil.format(new Date(), "yyyy-MM-dd") + "/";
		// 判断文件夹是否存在,不存在则
		File targetFile = new File(basePath + location);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }
		for(MultipartFile file : files) {
			FileUploadResponse rs = new FileUploadResponse();
			String contentType = file.getContentType();
	        String fileName = file.getOriginalFilename();
	        try {
	        	// java7中新增特性
	        	// ATOMIC_MOVE	原子性的复制
	        	// COPY_ATTRIBUTES	将源文件的文件属性信息复制到目标文件中
	        	// REPLACE_EXISTING	替换已存在的文件
	        	Files.copy(file.getInputStream(), Paths.get(uploadProperties.getBasePath() + location, fileName), StandardCopyOption.REPLACE_EXISTING);
	            rs.setContentType(contentType);
	            rs.setFileName(fileName);
	            rs.setUrl(Base64Util.encodeData(location + fileName) + fileName.substring(fileName.lastIndexOf(".")));
	            rs.setType("success");
	            log.info(JSON.toJSONString(rs));
	        } catch (Exception e) {
	        	rs.setType("fail");
	        	rs.setMsg("文件上传失败!");
	            log.error("上传文件失败," + e);
	        }
	        list.add(rs);
		}
        //返回json
        return list;
	}
	
	/**
	 * @Title: getFile 
	 * @Description: TODO(获取图片) 
	 * @param url
	 * @param filename
	 * @return ResponseEntity<?>    返回类型
	 */
	@GetMapping("/{filename:.+}")
	@ResponseBody
	public ResponseEntity<?> getFile(@PathVariable String filename) {
		try {  
	        return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(uploadProperties.getBasePath() + Base64Util.decodeData(filename)).toString()));  
	    } catch (Exception e) {  
	        return ResponseEntity.notFound().build();  
	    }  
	}
}
  

4、图片展示:

http://www.meatball.com/MjAxNy0xMC0xNC9zY3JlZW5zaG90MS5qcGc=.jpg

MjAxNy0xMC0xNC9zY3JlZW5zaG90MS5qcGc=.jpg为上面rs里的url属性,rs为返回消息vo,可以自行配置

转载于:https://my.oschina.net/qjedu/blog/1550704

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值