spring boot 上传图片

maven工程


1、添加依赖

        <dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>

</dependency>


2、配置application.properties文件

        #使用common-fileupload进行文件上传
        spring.http.multipart.enabled=false
        #file upload url
        file.upload.url=/files/
        #文件路径

        system.filepath=/data/web/webpicture


3、添加springMVC自定义配置

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration

public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*");
    }

    /**
     * 映射路径全词匹配
     * @param configurer
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }


    @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
    @ConditionalOnClass(value = ServletFileUpload.class)
    MultipartResolver multipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setResolveLazily(true);
        resolver.setMaxUploadSize(5242880);
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }
}

4、定义上传图片接口


@RestController
public class FileUploadController {


private Logger logger = LogManager.getLogger(FileUploadController.class);


@Value("${idea.url}")
protected String baseUrl;


@Value("${system.filepath}")
protected String systemFilepath;


@Value("${file.upload.url}")
protected String fileUploadUrl;


@ApiOperation("上传图片")
@PostMapping(value = "uploadImg")
@ApiImplicitParams({ @ApiImplicitParam(name = "file", value = "文件", paramType = "form", dataType = "__file") })
public @ResponseBody void uploadImg(
@RequestParam(required = false) CommonsMultipartFile file,
HttpServletRequest request, HttpServletResponse response)
throws Exception {


Admin user = SecurityContextUtil.getAdmin();//此处为 获取用户信息
String merchantId = user.getMerchantId(); // 用户信息中的商户ID
String accessToken = user.getAccessToken(); //用户信息中的token


long startTime = System.currentTimeMillis();
String path = systemFilepath + "/" + merchantId;
File fileme = new File(path + "/");
// 如果文件夹不存在则创建
if (!fileme.exists() && !fileme.isDirectory()) {
fileme.mkdirs();
logger.warn("创建文件目录" + fileme.getPath());
}
String cropSuffix = file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."),
file.getOriginalFilename().length());


if (!".PNG".equals(cropSuffix.toUpperCase())
&& !".JPG".equals(cropSuffix.toUpperCase())
&& !".JPEG".equals(cropSuffix.toUpperCase())
&& !".BMP".equals(cropSuffix.toUpperCase())
&& !".SVG".equals(cropSuffix.toUpperCase())
&& !".GIF".equals(cropSuffix.toUpperCase())
&& !".TIFF".equals(cropSuffix.toUpperCase())) {
response.getWriter()
.write("{\"status\":\"error\",\"message\":\"只支持上传png、jpg、jpeg、bmp、svg、gif、tiff格式图片\"}");
return;
}
String imgName = UUID.randomUUID().toString().replaceAll("-", "")
+ cropSuffix;
BufferedImage sourceImg = ImageIO.read(file.getInputStream());
File newFile = new File(path + "/" + imgName);
file.transferTo(newFile);
long endTime = System.currentTimeMillis();
System.out
.println("运行时间:" + String.valueOf(endTime - startTime) + "ms");
response.getWriter().write(
"{\"status\":\"success\",\"url\":\"" + request.getContextPath()
+ "/getPic?url=" + imgName + Const.ACCESS_TOKEN_PREFIX + accessToken +"\",\"width\":"
+ sourceImg.getWidth() + ",\"height\":"
+ sourceImg.getHeight() + "}");


}


@ApiOperation("裁剪图片")
@PostMapping(value = "croppic")
public @ResponseBody void croppic(Croppic croppic,
String flag, HttpServletRequest request,
HttpServletResponse response) throws Exception {


Admin user = SecurityContextUtil.getAdmin();//此处为 获取用户信息
String merchantId = user.getMerchantId(); // 用户信息中的商户ID
String accessToken = user.getAccessToken(); //用户信息中的token


String path = systemFilepath + "/" + merchantId + "/";
System.out.println("x:" + croppic.getImgX1() + ",y:"
+ croppic.getImgY1() + ",width:" + croppic.getCropW()
+ ",height:" + croppic.getCropH());
String proxyUrl = croppic.getImgUrl().split("&")[0];
String imgUrl = proxyUrl.substring(
proxyUrl.lastIndexOf("=") + 1,
proxyUrl.length());
String suffixName = imgUrl.substring(imgUrl.lastIndexOf(".") + 1,
imgUrl.length());
String url = UUID.randomUUID().toString().replaceAll("-", "") + "."
+ suffixName;
String sourcePath = path + imgUrl; // 原路径
String outPath = path + url; // 最后输出路径
CropImage.resizeImage(sourcePath, sourcePath, (int) croppic.getImgW(),
(int) croppic.getImgH(), suffixName.toUpperCase()); // 调整图片大小
if (!StringUtils.isEmpty(croppic.getRotation())) {
CropImage.rotateImage(sourcePath, sourcePath,
croppic.getRotation(), suffixName.toUpperCase()); // 调整图片旋转角度
}
CropImage.cutPic(sourcePath, outPath, croppic.getImgX1(),
croppic.getImgY1(), croppic.getCropW(),
(int) croppic.getCropH());
File oldFile = new File(path + imgUrl);
if (oldFile.isFile())
oldFile.delete();
String img = outPath;
String imgName;
String filesUrl = baseUrl + fileUploadUrl;


imgName = HttpClientUtil.doPostFile(filesUrl, Const.HEADER_X_SERVER,
accessToken, img);


response.getWriter().write(
"{\"status\":\"success\",\"url\":\"" + imgName
+ "\",\"myurl\":\"" + url + "\"}");


File newFile = new File(outPath);
if (newFile.isFile())
newFile.delete();
}


@ApiOperation("查看图片")
@ApiImplicitParam(name = "url", value = "图片名称(带后缀)", required = true, paramType = "query")
@GetMapping(value = "getPic")
public void getPic(
@ApiIgnore @RequestParam(value = "url", required = true) String url,
HttpServletResponse response) throws IOException {


Admin user = SecurityContextUtil.getAdmin();//此处为 获取用户信息
String merchantId = user.getMerchantId(); // 用户信息中的商户ID


String path = systemFilepath + "/" + merchantId + "/" + url;
File file = new File(path);
InputStream inStream = null;
try {
inStream = new FileInputStream(file);
} catch (Exception e) {
logger.warn("[图片:" + url + "没有找到,地址为:+" + path + "]");
return;
}
byte data[] = readInputStream(inStream);
response.setContentType("image/"
+ url.substring(url.lastIndexOf("."), url.length())); // 设置返回的文件类型
OutputStream os = response.getOutputStream();
os.write(data);
os.flush();
os.close();
inStream.close();
}


public static byte[] readInputStream(InputStream inStream) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = 0;
try {
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}


return outStream.toByteArray();
}


/**
*
* @param multipartFile
* @param path
* @param fileName
* @return
* @throws IOException
* 时间: 2018年3月1日 下午2:01:30
* 描述:
*/
public static String saveImg(MultipartFile multipartFile, String path,
String fileName) throws IOException {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
FileInputStream fileInputStream = (FileInputStream) multipartFile
.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(path + File.separator + fileName));
byte[] bs = new byte[1024];
int len;
while ((len = fileInputStream.read(bs)) != -1) {
bos.write(bs, 0, len);
}
bos.flush();
bos.close();
return fileName;
}



5、调整图片的工具类

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

public class CropImage {


public static void main(String[] args) throws Exception {
// cutPic("C:\\Users\\root\\Desktop\\111.jpg", "D:\\2.jpg", 100, 100, 100, 100);
rotateImage("C:\\Users\\root\\Desktop\\111.jpg", "D:\\2.jpg", 5,"jpg");
}


/**

* 作者: ydd
* @param srcFile 原图片路径 
* @param outFile 输出图片路径 
* @param x 图片x轴位置
* @param y 图片y轴位置
* @param width  图片裁剪框的宽度
* @param height 图片裁剪框的高度
* @return 
* 时间: 2018年3月1日 上午10:03:33
* 描述:
*/
public static boolean cutPic(String srcFile, String outFile, int x, int y, int width, int height) {
FileInputStream is = null;
ImageInputStream iis = null;
try {
// 如果源图片不存在
if (!new File(srcFile).exists()) {
return false;
}


// 读取图片文件
is = new FileInputStream(srcFile);


// 获取文件格式
String ext = srcFile.substring(srcFile.lastIndexOf(".") + 1);


// ImageReader声称能够解码指定格式
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(ext);
ImageReader reader = it.next();


// 获取图片流
iis = ImageIO.createImageInputStream(is);


// 输入源中的图像将只按顺序读取
reader.setInput(iis, true);


// 描述如何对流进行解码
ImageReadParam param = reader.getDefaultReadParam();


// 图片裁剪区域
Rectangle rect = new Rectangle(x, y, width, height);


// 提供一个 BufferedImage,将其用作解码像素数据的目标
param.setSourceRegion(rect);


// 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象
BufferedImage bi = reader.read(0, param);


// 保存新图片
File tempOutFile = new File(outFile);
if (!tempOutFile.exists()) {
tempOutFile.mkdirs();
}
ImageIO.write(bi, ext, new File(outFile));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (iis != null) {
iis.close();
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}


/**

* 作者: ydd 
* @param srcImgPath 原图片路径 
* @param distImgPath 转换大小后图片路径 
* @param width  转换后图片宽度 
* @param height 转换后图片高度 
* @param imgType 图片类型 "JPG"?"JPEG"
* @throws IOException 
* 时间: 2018年3月1日 上午10:03:33
* 描述: 调整图片大小
*/
public static void resizeImage(String srcImgPath, String distImgPath, int width, int height, String imgType) throws IOException {
File srcFile = new File(srcImgPath);
Image srcImg = ImageIO.read(srcFile);
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);


ImageIO.write(buffImg, imgType == "JPG"?"JPEG":imgType, new File(distImgPath));
}

/**

* 作者: ydd
* @param srcImgPath 原图片路径 
* @param distImgPath 转换后图片路径 
* @param degree 旋转角度
* @param imgType 图片类型 "JPG"?"JPEG"
* @throws IOException 
* 时间: 2018年3月1日 上午10:03:33
* 描述:
*/
public static void rotateImage(String srcImgPath, String distImgPath,final int degree, String imgType) throws IOException {
File srcFile = new File(srcImgPath);
Image srcImg = ImageIO.read(srcFile);
BufferedImage bufferedimage =  new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null),BufferedImage.TYPE_INT_RGB);   ;  
Graphics2D graphics2d = bufferedimage.createGraphics();
graphics2d.rotate(Math.toRadians(degree), srcImg.getWidth(null) / 2, srcImg.getHeight(null) / 2);
graphics2d.drawImage(srcImg, 0, 0, null);
        graphics2d.dispose();
        ImageIO.write(bufferedimage, imgType == "JPG"?"JPEG":imgType, new File(distImgPath));

}



6、切图请求实体

/**
 * 裁切图片请求实体 -- form表单提交
 * 
 * 时间: 2018年3月22日 上午10:28:37
 * 描述:
 */
@ApiModel(description = "裁切图片请求实体")
public class Croppic {


@ApiModelProperty(value = "图片路径")
private String imgUrl;

private int imgInitW;

private int imgInitH;

private double imgW;

private double imgH;

private int imgX1;

private int imgY1;

private int cropW;

private int cropH;

private int rotation;

        //setter和getter方法自己实现


}


7、http请求工具类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import java.io.*;

public class HttpClientUtil {


    private static Logger logger = LogManager.getLogger(HttpClientUtil.class);
    public static final String HTTP_STATUS = "httpStatus"; // 分类未发布
    public static final String HTTP_RESULT = "httpResult"; // 结果


    public static String doGet(String url) throws Exception {
        logger.info("url :" + url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        String result = null;
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
            logger.info("http status :" + statusCode);
            JSONObject parse = new JSONObject();
            parse.put(HTTP_STATUS, statusCode);
            parse.put(HTTP_RESULT, JSON.parseObject(result, Feature.OrderedField));


            result = parse.toJSONString();
            logger.debug("result:" + result);
        } catch (ClientProtocolException e) {
            throw new Exception("[网络连接失败:" + url + "]");
        }
        return result;
    }


    public static String doPost(String url, String header, String xtoken, String paramJson) throws Exception {
        logger.info("url :" + url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");


        if (!StringUtils.isEmpty(paramJson)) {
            httpPost.setEntity(new StringEntity(paramJson, "UTF-8"));
        }
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }


            logger.info("http status :" + statusCode);
            JSONObject parse = new JSONObject();
            parse.put(HTTP_STATUS, statusCode);
            parse.put(HTTP_RESULT, JSON.parseObject(result, Feature.OrderedField));
            if (HttpStatus.SC_OK == statusCode) { // 如果header为null 就是登陆
                Header head = response.getFirstHeader("X-Token");
                parse.put("xtoken", head.getValue());
            }
            result = parse.toJSONString();
            logger.debug("result:" + result);
        } catch (ClientProtocolException e) {
            throw new Exception("[网络连接失败:" + url + "]");
        }
        return result;
    }


    public static String inputStream2String(InputStream is) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }


    public static String doPostFile(String url, String header, String xtoken, String img) throws Exception {
        logger.info("url :" + url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        FileBody bin = new FileBody(new File(img));
        StringBody uploadFileName = new StringBody("localmedia", ContentType.create("text/plain", Consts.UTF_8));
        HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart("files", bin) //uploadFile对应服务端类的同名属性<File类型>
                .addPart("type", uploadFileName)//uploadFileName对应服务端类的同名属性<String类型>  
                .setCharset(CharsetUtils.get("UTF-8")).build();


        httpPost.setEntity(reqEntity);


        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
            System.err.println(result.indexOf("["));
            result = result.substring(result.indexOf("\"") + 1, result.lastIndexOf("\""));
            logger.info("http status :" + statusCode);
            logger.debug("result:" + result);
        } catch (ClientProtocolException e) {
            throw new Exception("[网络连接失败:" + url + "]");
        }
        return result;
    }


    public static String doPut(String url, String header, String xtoken, String paramJson) throws Exception {
        logger.info("url :" + url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        String result = null;
        httpPut.addHeader("Content-Type", "application/json;charset=UTF-8");


        if (!StringUtils.isEmpty(paramJson)) {
            httpPut.setEntity(new StringEntity(paramJson, "UTF-8"));
        }
        try {
            CloseableHttpResponse response = httpClient.execute(httpPut);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
            logger.info("http status :" + statusCode);
            JSONObject parse = new JSONObject();
            Header[] header1 = response.getHeaders("Msg");
            if (header1 != null && header1.length > 0) {
                parse.put("Msg", header1[0].getValue());
            }
            parse.put(HTTP_STATUS, statusCode);
            parse.put(HTTP_RESULT, JSON.parseObject(result, Feature.OrderedField));
            result = parse.toJSONString();
            logger.debug("result:" + result);
        } catch (ClientProtocolException e) {
            throw new Exception("[网络连接失败:" + url + "]");
        }
        return result;
    }


    public static String doDelete(String url, String header, String xtoken) throws Exception {
        logger.info("url :" + url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDel = new HttpDelete(url);
        String result = null;
        httpDel.addHeader("Content-Type", "application/json");


        try {
            CloseableHttpResponse response = httpClient.execute(httpDel);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
            logger.info("http status :" + statusCode);
            JSONObject parse = new JSONObject();
            parse.put(HTTP_STATUS, statusCode);
            parse.put(HTTP_RESULT, JSON.parseObject(result, Feature.OrderedField));


            result = parse.toJSONString();
            logger.debug("result:" + result);
        } catch (ClientProtocolException e) {
            throw new Exception("[网络连接失败:" + url + "]");
        }
        return result;
    }


}



8、前端使用 Croppic.js插件上传图片,直接下载插件简单修改即可


猜你喜欢

转载自blog.csdn.net/y_h_d/article/details/80053276