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

}
相关推荐
阿伟*rui25 分钟前
配置管理,雪崩问题分析,sentinel的使用
java·spring boot·sentinel
XiaoLeisj2 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
paopaokaka_luck2 小时前
【360】基于springboot的志愿服务管理系统
java·spring boot·后端·spring·毕业设计
dayouziei2 小时前
java的类加载机制的学习
java·学习
Yaml44 小时前
Spring Boot 与 Vue 共筑二手书籍交易卓越平台
java·spring boot·后端·mysql·spring·vue·二手书籍
小小小妮子~4 小时前
Spring Boot详解:从入门到精通
java·spring boot·后端
hong1616884 小时前
Spring Boot中实现多数据源连接和切换的方案
java·spring boot·后端
aloha_7895 小时前
从零记录搭建一个干净的mybatis环境
java·笔记·spring·spring cloud·maven·mybatis·springboot
记录成长java5 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet
睡觉谁叫~~~5 小时前
一文解秘Rust如何与Java互操作
java·开发语言·后端·rust