MultipartHttpServletRequest上传图片到文件服务器

前端请求File 选择图片上传

java 复制代码
 @RequestMapping("/save")
    @ResponseBody
    public  Map<String,Object> addSync(HttpServletRequest request, HttpServletResponse response) throws TokenTimeoutException, TokenMissException {
        UserBean user = this.detectUserBean(request).getUserBean();
        logger.info("图片开始上传!111111111111111111111111");
        Map<String,Object> result = new HashMap<>();

        String timeRoute = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String folder = "upload/"+user.getDefaultArea().getAreaCode()+"/replyPic/"+timeRoute + "/";
        try {

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile mf = multipartRequest.getFile("File");
            logger.info("图片开始上传!"+folder);
            Map<String, Object> a = FileUploadHandler.uploadPicHandler(mf, baseImgPath, folder,null);
            String picPath = a.get("picPath").toString();
            String ss = viewImgFileRootPath+picPath;
            logger.info("allPath->"+ss);
            a.put("allPath",viewImgFileRootPath+picPath);
            result.put("status",true);
            result.put("data",a );

        } catch (Exception e) {
            result.put("status",false);
        }
        return result;
    }
java 复制代码
package com.xjgzinfo.zhwwpt.s.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;


public final class FileUploadHandler {
	private static final Color TRANSLUCENT = new Color(Color.TRANSLUCENT);
	private static Logger logger = Logger.getLogger(FileUploadHandler.class);
	
	private FileUploadHandler(String fileName) {
	}
    
	/**
	 * 
	 * @Title: uploadPicHandler 
	 * @Description: 图片上传
	 * @param multipartFile
	 * @param targetDir 文件保存配置路径
	 * @param uploadDir 自定义路径
	 * @return
	 * @return: Map<String,Object>  code:0成功,1失败;error_message:失败提示内容;message:成功提示内容;picPath:成功相对路径,不包含文件保存配置路径
	 */

	public static Map<String,Object> uploadPicHandler(MultipartFile multipartFile,String targetDir,String uploadDir,String zplx){
		Map<String,Object> map = new HashMap<String,Object>();
		String fileSuffix = null;
		String originalFileName = multipartFile.getOriginalFilename();
		long originalFileSize = multipartFile.getSize();
		//验证图片后缀
		if(originalFileName.lastIndexOf(".") != -1){
			fileSuffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
			String tempFileSuffix = fileSuffix.substring(fileSuffix.lastIndexOf(".")+".".length());
			if(!verifyImageSuffix(tempFileSuffix)){
				map.put("code", "1");
				map.put("error_message", "非法的图片类型,仅允许后缀为jpg|jpeg|png|bmp|GIF|JPG|PNG|JPEG的类型图片");
				return map;
			}
		}else{
			map.put("code", "1");
			map.put("error_message", "非法的图片类型,仅允许后缀为jpg|jpeg|png|bmp|GIF|JPG|PNG|JPEG的类型图片");
			return map;
		}

		//验证图片大小
		if(originalFileSize >= 1024 * 1024 * 10){
			map.put("code", "1");
			map.put("error_message", "图片体积过大,请上传小于10M的图片");
			return map;
		}
						
		String targetFileName = System.currentTimeMillis()+fileSuffix;
		String targetFilePath = targetDir + uploadDir + targetFileName;
		File targetFile = new File(targetFilePath);
		if(!targetFile.getParentFile().exists()){
			targetFile.mkdirs();
		}
		try {
//			multipartFile.transferTo(targetFile);
			//给图片增加水印
			if ("身份证(正面)".equals(zplx)) {
				JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(multipartFile.getInputStream());
				BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
				int width = buffImg.getWidth();
				int height = buffImg.getHeight();
				// 创建相同大小的画图
				BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
				Graphics2D g = image.createGraphics();
				g.setBackground(TRANSLUCENT);
				g.dispose();
				WaterMarkImage wk = new WaterMarkImage();
				wk.drawString(image,"本图片仅限《XXXXX》使用!本图片仅限《XXXX》使用!本图片仅限《XXXX》使用!本图片仅限《XXXX》使用!本图片仅限《XXXXXX》使用!");
				Graphics2D gg = buffImg.createGraphics();
				gg.drawImage(image, 0, 0, null);
				g.dispose();
				ImageIO.write(buffImg, "jpg", targetFile);
			} else {
				multipartFile.transferTo(targetFile);
			}
			 
			
		} catch (Exception ex) {
			ex.printStackTrace();
			map.put("code", "1");
			map.put("error_message", "上传图片异常");
		}
		logger.info("上传的目标的文件:"+targetFile);
		if(targetFile.exists()){
			map.put("code", "0");
			map.put("message", "上传图片成功");
			map.put("picPath", uploadDir+targetFileName);
			map.put("absolutePath", targetFile.getAbsolutePath());
		}else{
			map.put("code", "1");
			map.put("error_message", "上传图片失败");
		}
		return map;
	}
	
	/**
	 * 验证图片后缀
	 * @param fileSuffix
	 * @return
	 */
	public static boolean verifyImageSuffix(String fileSuffix){
		boolean flag = false;
		String imageSuffix = "jpg|jpeg|png|bmp|GIF|JPG|PNG|JPEG";
		if(fileSuffix != null && fileSuffix.trim().length() > 0){
			flag = imageSuffix.contains(fileSuffix.trim());
		}
		return flag;
	}

	
	public static Map<String,Object> uploadFileHandler(MultipartFile multipartFile,String targetDir,String uploadDir){
		Map<String,Object> map = new HashMap<String,Object>();
		String fileSuffix = null;
		String originalFileName = multipartFile.getOriginalFilename();
		long originalFileSize = multipartFile.getSize();
		
		fileSuffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
						
		String targetFileName = System.currentTimeMillis()+fileSuffix;
		String targetFilePath = targetDir + uploadDir + targetFileName;
		File targetFile = new File(targetFilePath);
		if(!targetFile.getParentFile().exists()){
			targetFile.mkdirs();
		}
		try {
			multipartFile.transferTo(targetFile);
		} catch (Exception ex) {
			map.put("code", "1");
			map.put("error_message", "上传文件异常");
		}
		logger.info("上传的目标的文件:"+targetFile);
		if(targetFile.exists()){
			map.put("code", "0");
			map.put("message", "上传文件成功");
			map.put("picPath", uploadDir+targetFileName);
			map.put("absolutePath", targetFile.getAbsolutePath());
		}else{
			map.put("code", "1");
			map.put("error_message", "上传文件失败");
		}
		return map;
	}
	

	/**
	* 微信公众平台下载多媒体文件
	* @param downloadMediaUrl //接口地址
	* @param savePath //本地服务器保存地址
	* @author 
	* @throws Exception 
	*/
	public static Map<String,Object> downloadMedia(String downloadMediaUrl,String savePath){
		Map<String,Object> resp = new HashMap<String,Object>();
		try {
			System.out.println("==下载图片路径==>"+downloadMediaUrl);
			// 拼装请求地址
			URL url = new URL(downloadMediaUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET"); // 以Post方式提交表单,默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			
			BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
			File saveFie = new File(savePath);
			if (!saveFie.getParentFile().exists()){
		    	saveFie.getParentFile().mkdirs();
		    }
			FileOutputStream fos = new FileOutputStream(saveFie);
		    byte[] buf = new byte[8096];
		    int size = 0;
		    while ((size = bis.read(buf)) != -1)
	        fos.write(buf, 0, size);
	      	fos.close();
	      	bis.close();
	      	con.disconnect();
	      	System.out.println("==下载媒体文件成功,filePath==>" + saveFie);
			resp.put("code", "0");
		} catch (Exception e) {
			resp.put("code", "1");
			e.printStackTrace();
		}
		return resp; 
	}

}
相关推荐
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭5 分钟前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫22 分钟前
泛型(2)
java
南宫生31 分钟前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
转码的小石39 分钟前
12/21java基础
java
李小白661 小时前
Spring MVC(上)
java·spring·mvc
GoodStudyAndDayDayUp1 小时前
IDEA能够从mapper跳转到xml的插件
xml·java·intellij-idea
装不满的克莱因瓶2 小时前
【Redis经典面试题六】Redis的持久化机制是怎样的?
java·数据库·redis·持久化·aof·rdb
n北斗2 小时前
常用类晨考day15
java
骇客野人2 小时前
【JAVA】JAVA接口公共返回体ResponseData封装
java·开发语言
yuanbenshidiaos3 小时前
c++---------数据类型
java·jvm·c++