package com.fmkj.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @Auther: MQS
* @Date: 18/09/06 15:51
* @Description:
*/
@Component
public class ImageUtil {
private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
private static String location = "F:/image/userphoto/";
/**
* 上传图片
* @param multipartFile
* @return
*/
public static String upload(MultipartFile multipartFile){
if (multipartFile.isEmpty() || StringUtils.isEmpty(multipartFile.getOriginalFilename())){
return null;
}
String contentType = multipartFile.getContentType();
if (!contentType.contains("")){
return null;
}
String root_fileName = multipartFile.getOriginalFilename();
logger.info("上传图片:name={},type={}",root_fileName, contentType);
String fileName = StringUtils.getUUID() + ".png";
try {
File file = new File(location);
if (!file.exists()) {
file.mkdirs();
}
FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(location +"/"+ fileName));
byte[] bs = new byte[1024];
int len;
while ((len = fileInputStream.read(bs)) != -1){
bufferedOutputStream.write(bs, 0, len);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
return fileName;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 获取图片流
* @param name
* @param response
*/
public static void show(String name, HttpServletResponse response){
try {
response.setContentType("image/png");
File file = new File(location + name);
FileInputStream inputStream = new FileInputStream(file);
if (inputStream != null){
//得到文件大小
int i = inputStream.available();
byte[] data = new byte[i];
//读数据
inputStream.read(data);
inputStream.close();
OutputStream outputStream = response.getOutputStream();
outputStream.write(data);
outputStream.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}