`
dwj147258
  • 浏览: 192042 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

springmvc提交表单传输文件

阅读更多

首先我的html表单页面是这样的

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../index2Files/css/Home.css" rel="stylesheet" type="text/css">
<title>addDocument</title>
</head>
<body>
	<div style='overflow:hidden;margin-left:10px;padding-top:10px'>
	<form action="/exam/upload"  method="post" enctype="multipart/form-data"  id="uploadFile" target="test">
		<input id="filepath" type="text" length="30" class="input-bg" readonly="readonly" style="font-size:20px;color:#00d2ff"/>
		<input type="file"  name="file" class="file1" id="file" style="display:none;" size="28" onchange="getuploadFile()" />
		<input id="scan" type="button" class="zhixing-bt" value="浏览" onclick="file1()"/>
		<input id="import" type="submit" class="zhixing-bt" value="导入"/>
	</form>
	</div>
	<iframe name="test"></iframe>
	<script type="text/javascript" src="../js/jquery.js"></script>
	<script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
	<script type="text/javascript" src="../js/jquery.form.js"></script>
	
</body>
</html>

 里面的js函数可以先不用管它,不涉及到文件提交然后是后台接收

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

import main.java.bean.ExamQuestion;
import main.java.service.ExamService;
import main.java.util.BeanUtil;
import main.java.util.Util;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
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;

@Controller
@RequestMapping(value="/exam")
public class ExamController {
	private ExamService examService = (ExamService) BeanUtil.getBeanByName("examService");
	
	@RequestMapping(value="/upload" , method = RequestMethod.POST)
	@ResponseBody
	public JSONObject upload(@RequestParam("file")MultipartFile[] files , HttpServletRequest request, HttpServletResponse response){
		File orgFile = null ;
		 for(MultipartFile myfile : files){  
	            if(myfile.isEmpty()){  
	                System.out.println("文件未上传");  
	            }else{  
	                System.out.println("文件长度: " + myfile.getSize());  
	                System.out.println("文件类型: " + myfile.getContentType());  
	                System.out.println("文件名称: " + myfile.getName());  
	                System.out.println("文件原名: " + myfile.getOriginalFilename());  
	                System.out.println("========================================");  
	                //如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中  
	                String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");  
	                //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的  
	                	
	                InputStream in = null ;
	                FileOutputStream out = null ;
	                try{
	                in = myfile.getInputStream();
	                byte[] buffer = new byte[1024] ;
	                int length = 0 ; 
	                File filedir = new File(realPath);
	                if(!filedir.exists()){
	                	filedir.mkdirs();
	                }
	                orgFile = new File(realPath+"\\"+myfile.getOriginalFilename()) ;
	                out = new FileOutputStream(orgFile);
	                
	                while((length = in.read(buffer)) != -1){
	                	out.write(buffer, 0, length);
	                }
	                out.flush();
	                }
	                catch(Exception e ){
	                	e.printStackTrace();
	                }
	                finally{
	                	if(in!= null ){
	                		 try {
								in.close() ;
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                	}
	                	if(out!= null ){
	                		try {
								out.close();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                	}
	                
	                }
	            }  
	        }  
		
		JSONObject result = new JSONObject();
		result.put("success", "false") ;
		List<ExamQuestion> questionList = new ArrayList<ExamQuestion>();
		if( orgFile != null && orgFile.exists()){}
		if(questionList != null && questionList.size() > 0 ){
			examService.addQuestionBatch(questionList);
			result.put("success", "true") ;
		}
		return result ;
	}
}

 在这基础上,springmvc的配置需要添加如下信息

</bean>
  <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8"/>  
        <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="2000000"/>  
    </bean>  
      
    <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->  
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->  
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>  
            </props>  
        </property>  
    </bean>
分享到:
评论

相关推荐

    IDEA SpringMVC 实现文件的上传下载

    表单需设置`enctype="multipart/form-data"`,以便支持多部分数据传输。 5. **文件下载**: 下载文件时,Controller中需要返回一个链接,该链接指向服务器上待下载的文件。可以使用`@ResponseBody`和`...

    springMVC测试上传文件并在页面上显示

    总结来说,实现"springMVC测试上传文件并在页面上显示"的功能,需要处理前端的文件选择与提交,后端的文件接收、存储和解析,以及前端的数据展示。涉及的技术包括HTML5表单、Spring MVC的`@RequestParam`、`...

    SpringMVC文件上传案例

    在提交时,表单会将文件内容作为多部分数据发送。 4. **控制器处理**: 在SpringMVC的控制器类中,我们需要定义一个处理文件上传的HTTP请求的方法。该方法通常接收`@RequestParam("filename") ...

    SpringMVC-11 文件上传

    在本教程"SpringMVC-11 文件上传"中,我们将深入探讨如何使用Spring MVC来实现这一功能,特别是借助Apache Commons库中的`CommonsMultipartResolver`组件。 **一、MultipartResolver的角色** 在Spring MVC中,`...

    springmvc文件上传练习项目

    实现错误处理机制,如上传文件过大或类型不符时,返回适当的错误信息。 7. **前端表单**: 使用HTML的`&lt;form&gt;`标签,设置`enctype="multipart/form-data"`属性以支持文件上传。通过`&lt;input type="file"&gt;`创建文件...

    基于easyui+springmvc实现的文件管理系统

    在文件管理系统中,SpringMVC负责处理HTTP请求,将前端提交的数据与后端业务逻辑进行对接。开发者可以通过注解驱动的方式定义控制器,处理文件的增删改查操作,同时SpringMVC的依赖注入特性使得服务层和数据访问层的...

    springMVC 文件上传jar文件及源码

    在Spring MVC框架中,文件上传是一项常见的功能,用于接收用户通过表单提交的文件数据。在本主题中,我们将深入探讨如何使用Spring MVC的`fileupload`模块来实现这一功能,以及相关的源码分析。 首先,我们需要理解...

    springmvc接收ajax请求注意事项

    如果 Ajax 请求需要将一个表单中的数据传输到后台,那么需要使用 jQuery Form 插件,并将表单数据序列化后传输到服务器。例如: ```javascript function btnform() { $.ajax({ url: "${pageContext.request....

    SpringMVC精品资源--单文件上传,多文件上传,大文件上传,断点续传,文件秒传,图片上传.zip

    这个压缩包"SpringMVC精品资源--单文件上传,多文件上传,大文件上传,断点续传,文件秒传,图片上传.zip"包含了关于SpringMVC处理文件上传的各种技术点,这些都是开发者在实际项目中经常遇到的需求。 1. **单文件...

    springMVC中基于token防止表单重复提交方法

    1. 在SpringMVC配置文件中加入拦截器配置,拦截两类请求,一类是到页面的,一类是提交表单的。 2. 当转到页面的请求到来时,生成token的名字和token值,一份放到Redis缓存中,一份放传给页面表单的隐藏域。 3. 当...

    SpringMVC(九)文件上传和下载

    在Spring MVC中,文件上传通常涉及到前端表单提交和后端控制器处理。前端使用HTML5的`&lt;input type="file"&gt;`元素来选择用户想要上传的文件,然后通过AJAX或者传统的HTTP POST方式提交到服务器。在后端,Spring MVC...

    springmvc文件上传jar

    - 然后,创建一个Controller,定义一个处理文件上传的方法,该方法的参数应包含`@RequestParam("file") MultipartFile file`,其中"file"是前端表单提交的文件域名称。 - 在Controller方法内部,可以对`...

    关于springMVC的文件上传和下载

    当用户提交表单时,这些文件数据会作为多部分HTTP请求发送到服务器。Spring MVC提供了`@RequestParam("file") MultipartFile file`注解来接收这样的请求。 1. **文件上传配置**:在Spring MVC配置中,我们需要开启...

    springMVC-maven 简单的附件上传,文件本地磁盘存储,

    8. **前端页面**:创建一个HTML页面,包含一个表单,用户可以通过表单选择文件并提交上传。使用jQuery或者Ajax技术异步提交文件,显示上传结果。 9. **测试**:运行项目,通过浏览器访问前端页面,尝试上传文件。...

    springmvc+ajax带有文本域进行文件上传

    在现代Web应用中,文件上传是一...通过Ajax和特定的插件,用户可以在不刷新页面的情况下完成文件上传,同时提交文本信息,提高了交互性和效率。在实际开发中,还需要考虑到安全性、性能优化以及错误处理等多方面因素。

    SpringMVC文件上传

    SpringMVC文件上传知识点整理: SpringMVC框架是Java EE开发中常用的轻量级Web框架,其提供了强大的文件上传功能,能够处理多种文件上传的场景。本文档将详细讲解SpringMVC文件上传的实现原理、基本步骤、注意事项...

    SpringMVC单文件上传、多文件上传、文件列表显示、文件下载额

    你需要创建一个表单,包含一个`&lt;input type="file"&gt;`元素,用户选择文件后,表单提交到服务器。服务器端的Controller方法会接收到`MultipartFile`对象,你可以检查文件大小、类型,并将其保存到服务器指定的目录。 ...

    springmvc_helloWorld

    项目可以通过Tomcat等Servlet容器运行,访问预设的URL(如`http://localhost:8080/springmvc_helloWorld/helloWorld`)来启动表单,提交表单后,服务器将处理请求并返回响应。 通过这个"springmvc_helloWorld"项目...

    SpringMVC图片文件跨服务器上传

    在SpringMVC中实现图片文件的跨服务器上传是一项常见的任务,尤其在分布式系统或云环境下的应用中。这里我们将深入探讨如何配置和实现这一功能。 首先,为了支持文件上传,我们需要在上传服务器的`pom.xml`文件中...

Global site tag (gtag.js) - Google Analytics