通过SpringMVC进行文件的上传

还是直接上例子来说明:

1. 配置好web.xml

	  <servlet>
	  		<servlet-name>smartcity-upload</servlet-name>
		  	<servlet-class>
		   		org.springframework.web.servlet.DispatcherServlet
		  	</servlet-class>
			<init-param>  
                <param-name>contextConfigLocation</param-name>  
 				<param-value>/WEB-INF/config/spring-smartcity/smartcity-upload-servlet.xml</param-value>  
   			</init-param>  
	  		<load-on-startup>1</load-on-startup>
	 </servlet>
	 <servlet-mapping>
	  		<servlet-name>smartcity-upload</servlet-name>
	  		<url-pattern>/uploadFile.action</url-pattern>
	 </servlet-mapping>


2. 配置好smartcity-upload-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
	default-lazy-init="true">
	
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  		<!-- set the max upload size10MB -->
  		<property name="maxUploadSize">
   			<value>10485760</value>
  		</property>
    </bean>
	
	<bean name="fileUploadController" autowire-candidate="false" class="cn.ffcs.smartcity.cbusiness.web.action.FileUploadController">
  		<property name="commandClass" value="java.lang.Object" />
  		<property name="uploadDir">
			<value>${uploadDir}</value>
		</property>
 	</bean>
	
	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	  <property name="mappings">
	      <props>
	      <prop key="/uploadFile.action">
	             fileUploadController
	      </prop>
	   </props>
	  </property>
	 </bean>
	
</beans>


3. 在配置文件中加载properties文件中的参数代码如下:

	<bean id="propertyConfigurer_city"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="order" value="2" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="location">
			<value>classpath:/config.properties</value>
		</property>
	</bean>

4. 主体文件上传类

package cn.ffcs.smartcity.cbusiness.web.action;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

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

import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import cn.ffcs.smartcity.cbusiness.om.vo.FileUploadVO;
import cn.ffcs.smartcity.constants.CodeConstants;
import cn.ffcs.smartcity.constants.UploadFilePathConstants;
import cn.ffcs.smartcity.inner.vo.Exter;
import cn.ffcs.smartcity.util.PropertiesUtil;

public class FileUploadController extends SimpleFormController {

	private final static String CHARSET = "utf-8";
	private final static int THUMBNAIL_PIXEL = 100;
	private String uploadDir;
	
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object cmd, BindException errors)
			throws Exception {
		
		//获取上传文件的业务类型
		String businessType = request.getParameter("businessType");
		String result = "";
		if(businessType != null && !"".equals(businessType)) {
			//根据业务类型获取上传的路径
			String path = this.getPathByBusinessType(businessType);
			//上传文件
			FileUploadVO fileUploadVO = uploadFile(request,path);
			//根据业务类型判断是否有其他操作
			fileUploadVO.setBusinessType(businessType);
			fileUploadVO = this.doOtherOper(fileUploadVO);
			
			result = this.getResultString(fileUploadVO);
		} else {
			//如果业务类型为空时,返回提示信息
			result = "传递的businessType信息为空,上传失败.";
		}
		//返回客户端一些相关信息
		response = this.getResponse(response, result, CHARSET);
		return null;
	}

	private FileUploadVO uploadFile(HttpServletRequest request,String path) throws IOException {
		// 转型为MultipartHttpRequest:
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String originalFileName = "";
		String fileName = "";
		String fileType = "";
		FileUploadVO fileUploadVO = null;
		// 遍历所有文件域,获得上传的文件
		for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
			String key = (String) it.next();
			MultipartFile file = multipartRequest.getFile(key);
			if (file == null || file.isEmpty())
				continue;
			originalFileName = file.getOriginalFilename();
			fileType = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
			//检查上传文件的类型
			if(!this.checkCommenFileType(fileType)) {
				throw new IOException("传递的文件类型错误,类型为:" + fileType);
			}
			fileName = System.currentTimeMillis() +"_" + new Object().hashCode()+ new Random().nextLong() + "." + fileType;
			saveFile(file,path,fileName);
			
			//上传成功,记录对应的信息
			fileUploadVO = new FileUploadVO();
			fileUploadVO.setFilePath(path + fileName);
//			fileUploadVO.setUploadDir(uploadDir);
		}
		return fileUploadVO;
	}

	private void saveFile(MultipartFile file,String path,String fileName) throws IOException {
		
		File filePath = new File(uploadDir + path);
		if(!filePath.exists()) {
			filePath.mkdirs();
		}
		String localfileName = uploadDir + path + fileName;
		// 写入文件
		File fileAbsolutePath = new File(localfileName.toString());
		if(!fileAbsolutePath.exists()) {
			fileAbsolutePath.createNewFile();
		}
		//开始上传文件
		file.transferTo(fileAbsolutePath);
	}
	
	private FileUploadVO uploadThumbnailFile(FileUploadVO fileUploadVO) throws IOException {
		
		//获取大图片的文件地址
		String bigPicFilePath = uploadDir + fileUploadVO.getFilePath();
		File bigPicFile = new File(bigPicFilePath);
		//创建一个缩略图的文件
		File file = new File(uploadDir + fileUploadVO.getUploadPath());
		if(!file.exists()) {
			file.mkdirs();
		}
		
		String fileType = bigPicFilePath.substring(bigPicFilePath.lastIndexOf(".") + 1);
		//检查上传文件的类型
		if(!this.checkSpecialFileType(fileType)) {
			throw new IOException("传递的文件类型错误,类型为:" + fileType);
		}
		String fileName = System.currentTimeMillis() +"_" + new Object().hashCode()+ new Random().nextLong() + "." +  fileType;
		String smallPicPath = uploadDir + fileUploadVO.getUploadPath()  + fileName;
		/* 创建文件流信息 */
		File smallPicFile = new File(smallPicPath);
		if (!smallPicFile.exists()) {
			smallPicFile.createNewFile();
		}
		
		//以下为生成缩略图的方法
		AffineTransform transform = new AffineTransform();
		BufferedImage bis = ImageIO.read(bigPicFile);

		int w = bis.getWidth();
        int h = bis.getHeight();
        double scale = (double)w/h;
        int nw = THUMBNAIL_PIXEL;
        int nh = (nw * h) / w;
        if(nh > THUMBNAIL_PIXEL) {
            nh = THUMBNAIL_PIXEL;
            nw = (nh * w) / h;
        }
        double sx = (double)nw / w;
        double sy = (double)nh / h;
        transform.setToScale(sx,sy);
		AffineTransformOp ato = new AffineTransformOp(transform, null);
		BufferedImage bid = new BufferedImage(nw, nh,BufferedImage.TYPE_3BYTE_BGR);
		ato.filter(bis, bid);
		ImageIO.write(bid, fileType, smallPicFile);
		
		//设置好缩略图的地址
		fileUploadVO.setThumbnailFilePath(fileUploadVO.getUploadPath()  + fileName);
		return fileUploadVO;
	}
	
	private FileUploadVO doOtherOper(FileUploadVO fileUploadVO) throws IOException {
		
		if(fileUploadVO != null) {
			if(CodeConstants.S_BUSINESSTYPE_UNISERVALPHOTO.equals(fileUploadVO.getBusinessType())) {
				//判断是随手拍大图片上传之后,开始进行缩略图的压缩上传
				//设置缩略图上传的相对路径     
				fileUploadVO.setUploadPath(UploadFilePathConstants.UNIVERSAL_SMALL_PHOTO_PATH);
				fileUploadVO = this.uploadThumbnailFile(fileUploadVO);
			}
		}
		
		return fileUploadVO;
	}
	
	private String getPathByBusinessType(String businessType) {
		
		String path = UploadFilePathConstants.UPLOAD_FILE_DEFAULT_PATH;
		if(CodeConstants.S_BUSINESSTYPE_UNISERVALPHOTO.equals(businessType)) {
			path = UploadFilePathConstants.UNIVERSAL_BIG_PHOTO_PATH;
		}
		
		return path;
	}
	
	private String getResultString(FileUploadVO fileUploadVO) {
		
		StringBuffer sb = new StringBuffer();
		if(fileUploadVO != null) {
			if(fileUploadVO.getFilePath() != null && !"".equals(fileUploadVO.getFilePath())) {
				sb.append(fileUploadVO.getFilePath()).append(",");
			}
			if(fileUploadVO.getThumbnailFilePath() != null && !"".equals(fileUploadVO.getThumbnailFilePath())) {
				sb.append(fileUploadVO.getThumbnailFilePath()).append(",");
			}
			
		}
		return sb.toString();
	}

	private boolean checkCommenFileType(String fileType){
		boolean result = false;
		if(fileType != null) {
			fileType = fileType.toUpperCase();
			if("JPG".equals(fileType) || "PNG".equals(fileType) || "GIF".equals(fileType)
					|| "DOC".equals(fileType) || "DOCS".equals(fileType) || "XLS".equals(fileType) || "XLSX".equals(fileType)
					|| "PDF".equals(fileType)) {
				result = true;
			}
		}
		return result;
	}
	
	private boolean checkSpecialFileType(String fileType){
		boolean result = false;
		if(fileType != null) {
			fileType = fileType.toUpperCase();
			if("JPG".equals(fileType) || "PNG".equals(fileType) || "GIF".equals(fileType)) {
				result = true;
			}
		}
		return result;
	}
	
	private HttpServletResponse getResponse(HttpServletResponse response,String msg,String charset) throws IOException {
		
		if(msg != null && !"".equals(msg)) {
			byte[] bt = msg.getBytes(charset);
			response.getOutputStream().write(bt);
		}
		return response;
	}

	public String getUploadDir() {
		return uploadDir;
	}

	public void setUploadDir(String uploadDir) {
		this.uploadDir = uploadDir;
	}
	
}

5. 以下为测试该上传方法的单测类

package url;

import io.IoStreamUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * httpclient上传文件
 * @author linwei
 *
 */
public class MultipartEntityUtil {

	public static String postFile(File file,String url) throws ClientProtocolException, IOException {

		FileBody bin = null;
		HttpClient httpclient = new DefaultHttpClient();
//		httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
		HttpPost httppost = new HttpPost(url);
		if(file != null) {
			bin = new FileBody(file);
		}

		StringBody businessType = new StringBody("photo");
		System.out.println(Charset.defaultCharset());
		StringBody password = new StringBody("测试上大多数123。",Charset.forName("UTF-8"));
		
	    MultipartEntity reqEntity = new MultipartEntity();
	    reqEntity.addPart("businessType", businessType);
	    reqEntity.addPart("password", password);
	    reqEntity.addPart("data", bin);
	    httppost.setEntity(reqEntity);
	    System.out.println("执行: " + httppost.getRequestLine());
	    
	    HttpResponse response = httpclient.execute(httppost);
	    System.out.println("statusCode is " + response.getStatusLine().getStatusCode());
	    HttpEntity resEntity = response.getEntity();
	    System.out.println("----------------------------------------");
	    System.out.println(response.getStatusLine());
	    if (resEntity != null) {
	      System.out.println("返回长度: " + resEntity.getContentLength());
	      System.out.println("返回类型: " + resEntity.getContentType());
	      InputStream in = resEntity.getContent();
	      System.out.println("in is " + in);
	      System.out.println(IoStreamUtil.getStringFromInputStream(in));
	    }
	    if (resEntity != null) {
	      resEntity.consumeContent();
	    }
		return null;
	}
	
	public static void main(String[] args) throws ClientProtocolException, IOException {
	
		File file = new File("d:/test.jpg");
		String url = "http://localhost:8081/uploadFile.action";
		postFile(file,url); 
	}
	
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值