java之springmvc图片上传

图片上传功能是比较常用的技术,接触的两个项目都被项目经理要求写图片上传功能。

并且如果项目要求图片上传,一般紧随其后的还有下载和删除。

用到的东西还不一样

第一个项目是:使用springmvc完成图片上传

第二个项目是:使用struts2完成图片上传

第一个项目已经上线运行,保存实现便于日后参考,作为工具保存。

spring-selevet.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<property name="defaultEncoding" value="utf-8" />
       <property name="maxUploadSize" value="10485760000" />
       <property name="maxInMemorySize" value="40960" />
</bean>
CommonsMultipartResolver 这是一个上传文件的分解器,主要的作用是配置文件上传的一些属性
1.配置文件的编码方式 defaultEncoding
2.配置文件最大值     maxUploadSize
3.配置缓存           maxInMemorySize
注意:在这个bean中id一定要叫multipartResolver,否则会报错误。

上传文件需要的两个jar文件

    commons-fileupload-1.2.2.jar
    commons-io-1.3.2.jar

html:

<pre name="code" class="html"><!DOCTYPE HTML>
<html>
<body>	
	<div id="fileUploader" style="display:none">
		<input  name="file" type="file" accept="image/jpg,image/png" />
		<div class="easyui-progressbar" style="width:200px;"> </div>
	</div>		
</body>
</html>
Action:
package com.eznext.modul.telpipe.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.security.Principal;

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.eznext.core.web.ActionResult;
import com.eznext.modul.telpipe.service.FileService;

import javax.activation.MimetypesFileTypeMap;

@Controller 
@RequestMapping("/file")
public class FileAction {

	private static Logger logger = LoggerFactory
			.getLogger(FileAction.class);
	
	private int BUFFER_SIZE = 4096;
	@Autowired
	private FileService fileService;
	
	@ResponseBody
	@RequestMapping(value = "upload")  
	public ActionResult upload(@RequestParam("cate") String category, @RequestParam("file") MultipartFile file, HttpServletRequest request, ModelMap model) {  
		  
		//保存  
		try { 
			String fileName = this.fileService.getFilePath(category, file.getOriginalFilename());
			String path = this.fileService.resolveToPhysicalFileName(fileName);
			File targetFile = new File(path);  
			if(!targetFile.exists()){  
				targetFile.mkdirs();  
			}  
			file.transferTo(targetFile);
			return ActionResult.Succeed(fileName);
		} catch (Exception e) {  
			logger.warn("", e);
			return ActionResult.Failed(e);
		}  		
	}
	
	@RequestMapping(value = "req", method = RequestMethod.GET)
	public void download(@RequestParam("f") String filename,
			Principal principal, HttpServletResponse response) {
		try {			
			response.setHeader("Content-disposition", "attachment; filename=" + filename);
			String physicalFilename = this.fileService.resolveToPhysicalFileName(filename);
			File file = new File(physicalFilename);
			String contentType = new MimetypesFileTypeMap().getContentType(file);
			response.setContentType(contentType);
			OutputStream outStream = response.getOutputStream();
			byte[] buffer = new byte[BUFFER_SIZE];
			FileInputStream fs = new FileInputStream(file);
			int len = 0;
			while((len = fs.read(buffer, 0, BUFFER_SIZE)) > 0){
				outStream.write(buffer, 0, len);
			}
			fs.close();
			outStream.flush();
			outStream.close();
			
		} catch (Exception ex) {
			logger.warn("product_download", ex);
		}

	}
	
	@RequestMapping(value = "del", method = RequestMethod.GET)
	public ActionResult delete(@RequestParam("f") String filename,
			Principal principal, HttpServletResponse response) {
		try {
			this.fileService.deleteFile(filename);
			return ActionResult.Succeed();
		} catch (Exception ex) {
			logger.warn("product_download", ex);
			return ActionResult.Failed(ex);
		}

	}
}
抽个时间对以上代码进行详细解析,欧洲杯,NBA总决赛这几天都有,忙不过来了都。

 







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值