在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件
(http://commons.apache.org/proper/commons-fileupload/),另一个是Oreilly组织的COS框架的

1.Struts2的文件上传

Struts2本身并没提供上传的组件,我们可以通过调用上传框架来实现文件的上传,struts2默认是jakarta作为其文件上传的解析器。

jakarta是Commo-FileUpload的框架。如果要使用Commo-FileUpload框架来上传文件,只需将"commons-fileupload-1.2.1.jar"

和"commons-io-1.3.2.jar"两个jar复制到项目中的WEB-INF/lib目录下就可。我们这里上传就是基于Commo-FileUpload框架实现的。

首先我们建立一个上传的JSP页面:

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<title>文件上传</title>
</head>
<body>
<form action="upload.action" method="post" enctype="multipart/form-data"> <input type="file" name="file" />
<input type="submit" value="Submit" /> </form>
</body>
</html>

下面我们顺便介绍一下from 中enctype属性的含义:

 表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:
  1) application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的
值处理成URL编码方式。
  2) multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到
请求参数里。
  3) text/plain:这种方式主要适用于直接通过表单发送邮件的方式。
  文件上传是原理是通过为表单元素设置enctype=”multipart/form-data”属性,让表单提交的数据以二进制编码的方式提交,
      在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。
 
在我们建立upload.action之前先对struts.xml进行相应的设置,如下所示:
    <constant name="struts.multipart.maxSize" value="10701096"/>
<!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
<constant name="struts.multipart.saveDir " value="c:/temp" />
<!--静态属性设置添加以上设置--> <package name="upload" extends="struts-default">
<action name="upload" class="com.test.action.UploadAction" method="execute">
<!-- 动态设置savePath的属性值 -->
<param name="savePath">/upload</param>
<result name="success">/WEB-INF/success.jsp</result>
<result name="input">/upload.jsp</result>
<interceptor-ref name="fileUpload">
<!-- 文件过滤 -->
<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
<!-- 文件大小, 以字节为单位 -->
<param name="maximumSize">1025956</param>
</interceptor-ref>
<!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
<interceptor-ref name="defaultStack" />
</action>
</package>

Upload.action:

public class UploadAction extends ActionSupport {
private File file;//对应文件域和页面中file input的name保持一致
private String fileContentType;//前面的File属性的名字 + ContentType(固定的)
private String fileFileName;//前面的File属性的名字 + FileName(固定的)
private String savePath;//保存路径 @Override
public String execute() {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
// 建立文件输出流
fos = new FileOutputStream(getSavePath() + "\\" + getFileFileName());
// 建立文件上传流
fis = new FileInputStream(getFile());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} catch (Exception e) {
System.out.println("文件上传失败");
e.printStackTrace();
} finally {
fis.close();
fos.close();
}
return SUCCESS;
} /**
* 返回上传文件的保存位置
*
* @return
*/
public String getSavePath() throws Exception{
return ServletActionContext.getServletContext().getRealPath(savePath);
} public void setSavePath(String savePath) {
this.savePath = savePath;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
} }

最后顺便说一下上传多个文件,主要有以下两种方式:

1.数组

File[] file 文件
String[] fileFileName 文件名
String[] fileContentType 文件类型

2.集合

List<File> file 
List<String> fileFileName
List<String> fileContentType

 2.SpringMVC的文件上传

个人认为Spring mvc的文件上传要比struts2要方便多了。Spring mvc 支持web应用程序的文件上传功能,是由Spring内置的即插即用的MultipartResolver来实现的,

上传的时候就需要在Spring的ApplicationContext里面加上SpringMVC提供的MultipartResolver的声明。这样之后,客户端每次进行请求的时候,

SpringMVC都会检查request里面是否包含多媒体信息,如果包含了就会使用MultipartResolver进行解析,SpringMVC会使用一个支持文件处理的

MultipartHttpServletRequest来包裹当前的HttpServletRequest,然后使用MultipartHttpServletRequest就可以对文件进行处理了。

Spring MVC已经为我们提供了一个MultipartResolver的实现,我们只需要拿来用就可以了,那就是org.springframework.web.multipart.commons.CommsMultipartResolver。因为springMVC的MultipartResolver底层使用的是Commons-fileupload,所以还需要加入对Commons-fileupload.jar的支持。

首先我们还是要建立一个上传页面:
 
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<title>文件上传</title>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data"> <input type="file" name="file" />
<input type="submit" value="Submit" /> </form>
</body>
</html>

然后我们在SpringMVC的applicationContent配置文件中加入以下设置:

    <!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<!-- 以字节为单位的最大上传文件的大小 -->
<property name="maxUploadSize" value="100000" />
</bean>

CommonsMultipartResolver允许设置的属性有:
    defaultEncoding:表示用来解析request请求的默认编码格式,当没有指定的时候根据Servlet规范会使用默认值ISO-8859-1。

当request自己指明了它的编码格式的时候就会忽略这里指定的defaultEncoding。

uploadTempDir:设置上传文件时的临时目录,默认是Servlet容器的临时目录。
    maxUploadSize:设置允许上传的最大文件大小,以字节为单位计算。当设为-1时表示无限制,默认是-1。
    maxInMemorySize:设置在文件上传时允许写到内存中的最大值,以字节为单位计算,默认是10240。

创建一个controller(控制器)来处理文件上传请求,FileUploadController.java:

实现上传的方法如下:

@RequestMapping( value="/upload.do",method = { RequestMethod.POST })
public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) {
System.out.println("开始");
String path = request.getSession().getServletContext().getRealPath("upload");//上传的目录
String fileName = file.getOriginalFilename();//上传的文件名字
System.out.println(path);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("result");
}

到此 SpringMVC的上传也结束了,要比Struts2要简单多了吧。

Strut2 和Spring MVC 文件上传对比的更多相关文章

  1. Spring MVC 笔记 —— Spring MVC 文件上传

    文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...

  2. Spring MVC文件上传教程 commons-io/commons-uploadfile

    Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...

  3. 【Java Web开发学习】Spring MVC文件上传

    [Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...

  4. Spring mvc文件上传实现

    Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...

  5. Spring mvc 文件上传到文件夹(转载+心得)

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  6. spring mvc 文件上传 ajax 异步上传

    异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...

  7. spring mvc文件上传(单个文件上传|多个文件上传)

    单个文件上传spring mvc 实现文件上传需要引入两个必须的jar包    1.所需jar包:                commons-fileupload-1.3.1.jar       ...

  8. Spring MVC 文件上传 & 文件下载

    索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ...

  9. 【Spring】Spring MVC文件上传--整合bootstrap-fileinput和jQuery-File-Upload

    前言 这里分享两个使用Spring MVC进行文件上传的简单示例, 分别整合bootstrap-fileinput 和 Jquery File Upload , 代码十分简单, 都是入门的示例,因此这 ...

随机推荐

  1. linux时间自动同步

    1,修正本地时区及ntp服务 #yum -y install ntp#rm -rf /etc/localtime#ln -s /usr/share/zoneinfo/Asia/Shanghai /et ...

  2. sql server 查询字符串指定字符出现的次数

    这里提取指定符串"A"在字段中的出现次数SQL为: select len(keyword)-len(replace(keyword, 'A', ' ')) from 表 原理:用r ...

  3. oracle 11G创建表空间、用户、配置监听和TNS

    最近总在安装各种版本的oralce数据库做测试,11G,32位的,64位的,12C的,每次都折腾表空间,用户.tns啥的,这里记录下,再也不用现用现百度找了 一.创建表空间.用户  在plsql工具中 ...

  4. C#break、continue、return、goto

    1.break break语句会使运行的程序立即退出包含在其中的最内层循环(结束此次循环且结束该循环控制体)或者switch语句 ; ; j < ; j++) { i++; )break; Co ...

  5. 04_线程的创建和启动_使用Callable和Future的方式

    [简述] 从java5开始,java提供了Callable接口,这个接口可以是Runnable接口的增强版, Callable接口提供了一个call()方法作为线程执行体,call()方法比run() ...

  6. ubuntu16.04无法连接无线的问题解决方式以及QQ的安装

    0x01 首先我是安装了win10与ubuntu16.04的双系统,不过遇到的问题有启动项与无线连接的问题,今天说一下联网的问题. 连接宽带是正常的,只需要操作sudo pppoeconf 这条命令即 ...

  7. Wix: Show conditional message box

    For example: Scenario: Show message box only during installation and MYPROPERTY has to be equal to & ...

  8. Apache(一)

    以下介绍是基于centos,Apache/2.2.15,进行解释 (资料来自www.netcraft.com) Apache 模块化的软件 Apache=core+module(内核+模块) core ...

  9. 在LaTeX中利用preview宏包和tikz宏包生成单图pdf

    有时候我们利用tikz宏包画出的图片后,只想生成一个单图pdf,而且pdf的页面大小与图片相同,以便于以后再次用latex插入. 可以与preview宏包进行搭配,页面大小由图像大小决定,可以通过改变 ...

  10. 【转】c#文件操作大全(一)

    1.创建文件夹//using System.IO;Directory.CreateDirectory(%%1); 2.创建文件//using System.IO;File.Create(%%1); 3 ...