用流的方式上传图片

1、表单
    [1].发送的请求必须是post请求
    [2].编码的方式要使用multipart/form-data的形式
    [3].使用type="file"的input标签生成文件上传框

<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
	<!-- 文件上传框提交的数据不要注入到String类型的logoPath属性中 -->
	<label for="logoPathInputId" class="col-lg-2 control-label">选择图片</label>
	<div class="col-lg-10">
		<input id="logoPathInputId"  type="file" name="logoFile"/>
	</div>
</form>

2、SpringMVC配置文件
    [1].配置bean:org.springframework.web.multipart.commons.CommonsMultipartResolver

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"/>
</bean>

[2].引入commons-fileupload组件的依赖

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

3、handle方法:使用RequestParam注解接收
    [1].常规数据:
        ①封装到实体类中
    [2].文件数据:
        ①参数类型:org.springframework.web.multipart.MultipartFile

4、文件复制相关
(1)图片压缩
    [1]目的:让所有的图片的长宽都按照比例缩放。
    [2]使用resizeImages()工具方法

/**
* 将图片压缩按本来的长宽比例压缩为100宽度的jpg图片
* @param inputStream
* @param realPath /surveyLogos目录的真实路径,后面没有斜杠
* @return 将生成的文件路径返回 surveyLogos/4198393905112.jpg
*/
public static String resizeImages(InputStream inputStream, String realPath) {
		
	OutputStream out = null;
		
	try {
		//1.构造原始图片对应的Image对象
		BufferedImage sourceImage = ImageIO.read(inputStream);

		//2.获取原始图片的宽高值
		int sourceWidth = sourceImage.getWidth();
		int sourceHeight = sourceImage.getHeight();
			
		//3.计算目标图片的宽高值
		int targetWidth = sourceWidth;
		int targetHeight = sourceHeight;
			
		if(sourceWidth > 100) {
			//按比例压缩目标图片的尺寸(可以按照需求进行设置)
			targetWidth = 100;
			targetHeight = sourceHeight/(sourceWidth/100);	
		}
			
		//4.创建压缩后的目标图片对应的Image对象
		BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
			
		//5.绘制目标图片
		targetImage.getGraphics().drawImage(sourceImage, 0, 0, targetWidth, targetHeight, null);
			
		//6.构造目标图片文件名
		String targetFileName = System.nanoTime() + ".jpg";
			
		//7.创建目标图片对应的输出流
		out = new FileOutputStream(realPath+"/"+targetFileName);
			
		//8.获取JPEG图片编码器
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			
		//9.JPEG编码
		encoder.encode(targetImage);
			
		//10.返回文件名(可以根据需求进行命名)
		return "img/"+targetFileName;
			
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	} finally {
		//10.关闭流
		if(out != null) {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
			
	}
}

[3]有两个API需要手动导入
        import com.sun.image.codec.jpeg.JPEGImageEncoder;
        import com.sun.image.codec.jpeg.JPEGCodec;
[4]在Web工程的src/main/webapp目录下创建img目录(根据返回文件的名称设置return "img/"+targetFileName;)
[5]resizeImages()工具方法的功能
        执行图片压缩
        将压缩后的图片数据写入到指定的位置
        返回一个字符串,这个字符串可以直接用于设置对象的logoPath属性
[6]虚拟路径转换为真实路径
        声明一个字符串保存虚拟路径
        获取ServletContext对象
        调用ServletContext对象的getRealPath(String virtualPath)方法获取真实路径

5、保存文件路径

    @RequestMapping("...")
	public String saveObject(HttpServletRequest request, MultipartFile logoFile, HttpSession session, Object object) throws IOException {
		
		//1.检查用户是否上传了图片
		boolean empty = logoFile.isEmpty();
		
		//2.如果用户上传了图片
		if(!empty) {
			
			//=======上传文件验证====
			//i.文件大小验证
			//①检查上传的文件大小是否满足要求
			long size = logoFile.getSize();
			
			//②如果不满足要求,则抛出异常
			if(size > 100*1024) { //(100kb)
				throw new FileTooLargeSaveException("文件太大");
			}
			
			//ii.文件类型验证
			//①检查上传的文件类型是否满足要求
			String contentType = logoFile.getContentType();
			
			//②如果不满足要求,则抛出异常
			//image/png,image/gif,image/jpeg
			if(!contentType.startsWith("image/")) {
				throw new FileTypeInvalidSaveException("文件格式不对");
			}
				
			//3.获取上传图片的输入流
			InputStream inputStream = logoFile.getInputStream();
			
			//4.将虚拟路径转换为真实路径
			String virtualPath = "/img";
			ServletContext servletContext = session.getServletContext();
			String realPath = servletContext.getRealPath(virtualPath);
			
			//5.执行图片压缩
			String logoPath = DataprocessUtils.resizeImages(inputStream, realPath);
			
			//6.使用工具方法返回的字符串设置object对象的logoPath属性
			//※这里的set操作是在if中,不满足条件时将保持默认值
			object.setLogoPath(logoPath);	
		}

		//7.保存object对象
		...
		
		return "redirect:/index.jsp";
	}

 

转载于:https://my.oschina.net/u/3283213/blog/1569164

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值