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

}
相关推荐
不是二师兄的八戒13 分钟前
本地 PHP 和 Java 开发环境 Docker 化与配置开机自启
java·docker·php
爱编程的小生25 分钟前
Easyexcel(2-文件读取)
java·excel
带多刺的玫瑰42 分钟前
Leecode刷题C语言之统计不是特殊数字的数字数量
java·c语言·算法
计算机毕设指导61 小时前
基于 SpringBoot 的作业管理系统【附源码】
java·vue.js·spring boot·后端·mysql·spring·intellij-idea
Gu Gu Study1 小时前
枚举与lambda表达式,枚举实现单例模式为什么是安全的,lambda表达式与函数式接口的小九九~
java·开发语言
Chris _data1 小时前
二叉树oj题解析
java·数据结构
牙牙7052 小时前
Centos7安装Jenkins脚本一键部署
java·servlet·jenkins
paopaokaka_luck2 小时前
[371]基于springboot的高校实习管理系统
java·spring boot·后端
以后不吃煲仔饭2 小时前
Java基础夯实——2.7 线程上下文切换
java·开发语言
进阶的架构师2 小时前
2024年Java面试题及答案整理(1000+面试题附答案解析)
java·开发语言