欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springmvc3实现文件上传 博客分类: spring springmvcjsonservlet 

程序员文章站 2024-03-16 19:33:04
...
Spring自己封装了文件上传功能,可以利用
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
MultipartFile multFile = multiRequest.getFile("imgFile");

需要在springmvc-servlet.xml里配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

结合iframe实现局部刷新上传

代码:

1.JSP页面:
<form:form method="post" action="${ctx}/wzxxfbpdtp/save" target="hidden_frame" id="pdtpNewForm" enctype="multipart/form-data" modelAttribute="wzXxfbPdtp">
		<div class="pageContent" layoutH="30">
		<div class="pageFormContent" align="center" style="overflow: hidden;">
			<input type="hidden" name="imgPath" id="imgPath" />
			<table align="center" width="500px" height="300px" border="0" cellpadding="0" cellspacing="0" style="margin-top: 10px;text-align: center;border-spacing: 10px;">
				
				
				<tr>
					<td width="70px">选择图片</td>
					<td colspan="2"><input id="imgFile" name="imgFile" type="file" /></td>
				</tr>
			</table>
		</div>
		</div>
		<iframe name="hidden_frame" id="hidden_frame" src="message.html" style="display:none"></iframe>
		
	</form:form>


2 controller后台:

/** 保存新增,@Valid标注spirng在绑定对象时自动为我们验证对象属性并存放errors在BindingResult  */
	@RequestMapping(value = "/save")
	public String create(ModelMap model,@Valid WzXxfbPdtp wzXxfbPdtp,HttpServletRequest request,HttpServletResponse response)throws Exception  {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
		MultipartFile multFile = multiRequest.getFile("imgFile");
		// 扩展名格式:
		String extName = "";
		String message = "";
		String newName = "";
		boolean flag = true;
		//取得上传的文件名
		String fileName = multFile.getOriginalFilename();
		if(fileName != null && !"".equals(fileName.trim())){
			//上传文件的大小
			long size = multFile.getSize();
			if(size > (1024*1024)){
				message = "只允许上传1M之内的图片";
				flag = false;
			}
			if (fileName.lastIndexOf(".") >= 0) {
				extName = fileName.substring(fileName.lastIndexOf("."));
			}
			//定义允许上传的文件类型
			List<String> fileTypes = new ArrayList<String>();
			fileTypes.add(".jpg");
			fileTypes.add(".jpeg");
			fileTypes.add(".gif");
			fileTypes.add(".png");
			if(!fileTypes.contains(extName.toLowerCase())){
				message = "只允许上传jpg,jpeg,gif,png格式的图片";
				flag = false;
			}
			String root=request.getSession().getServletContext().getRealPath("");
			String savePath = root+File.separator+"pdtpFolder"+File.separator;
			File f1 = new File(savePath);
			if (!f1.exists()) {
				f1.mkdirs();
			}
			if(flag){
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS");
				Calendar calendar = Calendar.getInstance();
				//以当前时间为文件名 格式如:2011-09-03-19-30-36047 
				newName = df.format(calendar.getTime());
				//newName = UUID.randomUUID().toString();
				File newFile = new File(savePath + newName + extName);
				try {
					multFile.transferTo(newFile);
				} catch (IllegalStateException e) {
					e.printStackTrace();
					flag = false;
				} catch (IOException e) {
					e.printStackTrace();
					flag = false;
				}
				//设置图片的相对地址
				wzXxfbPdtp.setTpdz("pdtpFolder/"+newName+extName);
				//图片原名称
				wzXxfbPdtp.setTpmc(fileName);
				//设置ID与新生成的图片名
				wzXxfbPdtp.setPkid(newName);
				wzXxfbPdtpManager.save(wzXxfbPdtp);
			}
		}
//		dwzCallback(model,CREATED_SUCCESS);
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.write("<script>parent.callback('"+flag+"','"+message+"')</script>");
//		return LIST_ACTION;
		return null;
	}


3 springmvc-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"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
    default-autowire="byName"   >

	<!-- 开启支持@NumberFormat @DateTimeFormat @Valid标注 ,@DateTimeFormat用于bean 日期属性的格式化,请查看: http://static.springsource.org/spring/docs/3.0.2.RELEASE/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-config-->
    <mvc:annotation-driven validator="validator"/>

	<!-- 自动搜索@Controller标注的类 -->
	<context:component-scan base-package="com.**.controller"/>
	
	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
		<!-- 拦截器注册 -->
		<property name="interceptors">
			<bean class="javacommon.springmvc.interceptor.SharedRenderVariableInterceptor"/>
		</property>
	</bean>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
	
    <!-- 根据客户端的不同的请求决定不同的view进行响应, 如 /blog/1.json /blog/1.xml -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    	<property name="ignoreAcceptHeader" value="true"/>
		<property name="defaultContentType" value="text/html"/>
		
    	<!-- 扩展名至mimeType的映射,即 /user.json => application/json -->
		<property name="mediaTypes">
			<map>
				<entry key="json" value="application/json" />
				<entry key="xml" value="application/xml" />
			</map>
		</property>
		<!-- 用于开启 /userinfo/123?format=json 的支持 -->
		<property name="favorParameter" value="true"/>
		<property name="viewResolvers">
			<list>
				<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
			    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
			        <property name="prefix" value="/pages"/>
			        <property name="suffix" value=".jsp"/>
			    </bean>
			</list>
		</property>
		<property name="defaultViews">
			<list>
				<!-- for application/json -->
				<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
				<!-- for application/xml -->
				<!-- 
				<bean class="org.springframework.web.servlet.view.xml.MarshallingView" >
					<property name="marshaller">
						<bean class="org.springframework.oxm.xstream.XStreamMarshaller"/>
					</property>
				</bean>
				 -->
			</list>
		</property>
    </bean>
    
    <!-- Mapping exception to the handler view -->
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
            </props>
        </property>
    </bean>
        
</beans>



Springmvc3实现文件上传
            
    
    博客分类: spring springmvcjsonservlet 


###############################################################
使用DiskFileItemFactory 及ServletFileUpload 组件进行上传
需要注意的是:所有的Form表单数据不再会自动绑定赋值,需要手动去设置值,还有就是不需要在springmvc-servlet.xml里配置:<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

后台处理类:

@Controller
@RequestMapping("/wzxxfbpdtp")
public class WzXxfbPdtpController extends BaseRestSpringController<WzXxfbPdtp,java.lang.String>{
//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = ""; 
	private WzXxfbPdtpManager wzXxfbPdtpManager;
	private final String LIST_ACTION = "redirect:/wzxxfbpdtp/manager";
	/** 
	 * 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写
	 **/
	public void setWzXxfbPdtpManager(WzXxfbPdtpManager manager) {
		this.wzXxfbPdtpManager = manager;
	}
		String extName = "";
		String message = "";
		boolean flag = true;
		Iterator<FileItem> it = fileList.iterator();
		while (it.hasNext()) {
			FileItem item = it.next();
			//给取表单域的值,赋给wzXxfbPdtp对象
			setFormFields(wzXxfbPdtp, item);
			// 如果是文件类型字段
			if (!item.isFormField()) {
				name = item.getName();
				long size = item.getSize();
				if(size>(1024*1024)){
					message="文件"+item.getName()+"大超过了1M,上传失败!";
					json.put("statusCode", "300");
					json.put("message", message);
					flag = false;
					break;
				}
				// 扩展名格式:
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				// 定义允许上传的文件类型
				List<String> fileTypes = new ArrayList<String>();
				fileTypes.add(".jpg");
				fileTypes.add(".jpeg");
				fileTypes.add(".gif");
				fileTypes.add(".png");
				if(!fileTypes.contains(extName.toLowerCase())){
					message = "只允许上传jpg,jpeg,gif,png格式的图片";
					json.put("statusCode", "300");
					json.put("message", message);
					flag = false;
					break;
				}
				if(flag) {
					DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS");
					Calendar calendar2 = Calendar.getInstance();
					//以当前时间为文件名 格式如:2011-09-03-19-30-36047 
					newName = df2.format(calendar2.getTime());
					File newFile = new File(savePath+"/"+folderName+"/" + newName + extName);
					item.write(newFile);
					//设置图片的相对地址
					wzXxfbPdtp.setTpdz(rootFile.getName()+"/"+folderName+"/"+newName+extName);
					//图片原名称
					wzXxfbPdtp.setTpmc(name);
				} 
			}
		}
		if(flag){
			wzXxfbPdtpManager.save(wzXxfbPdtp);
			json.put("navTabId", "BM01040000");
			json.put("statusCode", "200");
			json.put("callbackType", "closeCurrent");
			json.put("message", CREATED_SUCCESS);
		}
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.write(json.toString());
		out.flush();
		out.close();
		return null;
	}
/*
	 * 取得Form表单各文本域的值,赋给wzXxfbPdtp对象
	 */
	private void setFormFields(WzXxfbPdtp wzXxfbPdtp, FileItem item) throws UnsupportedEncodingException {
		if(item.isFormField()){
			String field = item.getFieldName();
			String temp;
			if(field.equals("zzdm")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setZzdm(temp);
			}
			if(field.equals("zzjc")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setZzjc(temp);
			}
			if(field.equals("bmdm")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setBmdm(temp);
			}
			if(field.equals("bmjc")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setBmjc(temp);
			}
			if(field.equals("tpbt")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setTpbt(temp);
			}
			if(field.equals("tplj")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setTplj(temp);
			}
			if(field.equals("kd")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setKd(Integer.parseInt(temp));
			}
			if(field.equals("gd")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setGd(Integer.parseInt(temp));
			}
			if(field.equals("sfpd")){
				temp = item.getString("utf-8");
				wzXxfbPdtp.setSfpd(temp);
			}
		}
	}
	
//删除本地图片文件
	private void deleteLocalFile(HttpServletRequest request, WzXxfbPdtp pdtp) {
		String	path = pdtp.getTpdz();
		String	root = request.getSession().getServletContext().getRealPath("");
		File rootFile =  new File(root);
		//得到图片存放的完整路径

		String savePath = rootFile.getParent()+ConstantUtils.getFilePath()+"/"+path;
		File f1 = new File(savePath);
		if(f1.exists()){
			f1.delete();
		}
	}


页面显示跟上图一样
  • Springmvc3实现文件上传
            
    
    博客分类: spring springmvcjsonservlet 
  • 大小: 64.7 KB