java file类型怎么把 File 类型转 MultipartFile

51058人阅读
Java基础编程(41)
第一点:Java代码实现文件上传
& FormFile file=manform.getFile();&
&&String newfileName =
&&String newpathname=
&&String fileAddre=&/numUp&;
&&&InputStream stream = file.getInputStream();// 把文件读入
&&& String filePath = request.getRealPath(fileAddre);//取系统当前路径
&&&&&&&&& File file1 = new File(filePath);//添加了自动创建目录的功能
&&&&&& ((File) file1).mkdir();&&&
&&& newfileName = System.currentTimeMillis()
&&&&&+ file.getFileName().substring(
&&&&&&&file.getFileName().lastIndexOf('.'));
&&&ByteArrayOutputStream baos = new ByteArrayOutputStream();
&&&OutputStream bos = new FileOutputStream(filePath + &/&
&&&&&+ newfileName);
&&&newpathname=filePath+&/&+newfileN
&&&System.out.println(newpathname);
&&&// 建立一个上传文件的输出流
&&& System.out.println(filePath+&/&+file.getFileName());
&&&int bytesRead = 0;
&&&byte[] buffer = new byte[8192];
&&&while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
&&&&bos.write(buffer, 0, bytesRead);// 将文件写入服务器
&&&bos.close();
&&&stream.close();
&&& } catch (FileNotFoundException e) {
&&&e.printStackTrace();
&&} catch (IOException e) {
&&&e.printStackTrace();
第二点:Jsp页面上实现文件上传
package com.vogoal.
import java.io.BufferedOutputS
import java.io.F
import java.io.FileOutputS
import java.io.IOE
import java.text.SimpleDateF
import java.util.ArrayL
import java.util.D
import java.util.H
import javax.servlet.ServletInputS
import javax.servlet.http.HttpServletR
public class JspFileUpload {
&&&&/** request对象 */
&&&&private HttpServletRequest request =
&&&&/** 上传文件的路径 */
&&&&private String uploadPath =
&&&&/** 每次读取得字节的大小 */
&&&&private static int BUFSIZE = 1024 * 8;
&&&&/** 存储参数的Hashtable */
&&&&private Hashtable paramHt = new Hasptable();
&&&&/** 存储上传的文件的文件名的ArrayList */
&&&&private ArrayList updFileArr = new ArrayList();
&&&& * 设定request对象。
&&&& * @param request
&&&& *& && && && &HttpServletRequest request对象
&&&&public void setRequest(HttpServletRequest request) {
&&&&&&&&this.request =
&&&& * 设定文件上传路径。
&&&& * @param path
&&&& *& && && && &用户指定的文件的上传路径。
&&&&public void setUploadPath(String path) {
&&&&&&&&this.uploadPath =
&&&& * 文件上传处理主程序。�������B
&&&& * @return int 操作结果 0 文件操作成功;1 request对象不存在。 2 没有设定文件保存路径或者文件保存路径不正确;3
&&&& *& && && &没有设定正确的enctype;4 文件操作异常。
&&&&public int process() {
&&&&&&&&int status = 0;
&&&&&&&&// 文件上传前,对request对象,上传路径以及enctype进行check。
&&&&&&&&status = preCheck();
&&&&&&&&// 出错的时候返回错误代码。
&&&&&&&&if (status != 0)
&&&&&&&&&&&&
&&&&&&&&try {
&&&&&&&&&&&&// ��参数或者文件名�u��
&&&&&&&&&&&&String name =
&&&&&&&&&&&&// 参数的value
&&&&&&&&&&&&String value =
&&&&&&&&&&&&// 读取的流是否为文件的标志位
&&&&&&&&&&&&boolean fileFlag =
&&&&&&&&&&&&// 要存储的文件。
&&&&&&&&&&&&File tmpFile =
&&&&&&&&&&&&// 上传的文件的名字
&&&&&&&&&&&&String fName =
&&&&&&&&&&&&FileOutputStream baos =
&&&&&&&&&&&&BufferedOutputStream bos =
&&&&&&&&&&&&// ��存储参数的Hashtable
&&&&&&&&&&&&paramHt = new Hashtable();
&&&&&&&&&&&&updFileArr = new ArrayList();
&&&&&&&&&&&&int rtnPos = 0;
&&&&&&&&&&&&byte[] buffs = new byte[BUFSIZE * 8];
&&&&&&&&&&&&// �取得ContentType
&&&&&&&&&&&&String contentType = request.getContentType();
&&&&&&&&&&&&int index = contentType.indexOf(&boundary=&);
&&&&&&&&&&&&String boundary = &--& + contentType.substring(index + 9);
&&&&&&&&&&&&String endBoundary = boundary + &--&;
&&&&&&&&&&&&// �从request对象中取得流。
&&&&&&&&&&&&ServletInputStream sis = request.getInputStream();
&&&&&&&&&&&&// 读取1行
&&&&&&&&&&&&while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) {
&&&&&&&&&&&&&&&&String strBuff = new String(buffs, 0, rtnPos);
&&&&&&&&&&&&&&&&// 读取1行数据�n��
&&&&&&&&&&&&&&&&if (strBuff.startsWith(boundary)) {
&&&&&&&&&&&&&&&&&&&&if (name != null && name.trim().length() & 0) {
&&&&&&&&&&&&&&&&&&&&&&&&if (fileFlag) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&bos.flush();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&baos.close();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&bos.close();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&baos =
&&&&&&&&&&&&&&&&&&&&&&&&&&&&bos =
&&&&&&&&&&&&&&&&&&&&&&&&&&&&updFileArr.add(fName);
&&&&&&&&&&&&&&&&&&&&&&&&} else {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&Object obj = paramHt.get(name);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&ArrayList al = new ArrayList();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&if (obj != null) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&al = (ArrayList)
&&&&&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&&&&&al.add(value);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&System.out.println(value);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&paramHt.put(name, al);
&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&name = new String();
&&&&&&&&&&&&&&&&&&&&value = new String();
&&&&&&&&&&&&&&&&&&&&fileFlag =
&&&&&&&&&&&&&&&&&&&&fName = new String();
&&&&&&&&&&&&&&&&&&&&rtnPos = sis.readLine(buffs, 0, buffs.length);
&&&&&&&&&&&&&&&&&&&&if (rtnPos != -1) {
&&&&&&&&&&&&&&&&&&&&&&&&strBuff = new String(buffs, 0, rtnPos);
&&&&&&&&&&&&&&&&&&&&&&&&if (strBuff.toLowerCase().startsWith(
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&content-disposition: form- &)) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&int nIndex = strBuff.toLowerCase().indexOf(
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&name=\&&);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&int nLastIndex = strBuff.toLowerCase().indexOf(
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\&&, nIndex + 6);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&name = strBuff.substring(nIndex + 6, nLastIndex);
&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&int fIndex = strBuff.toLowerCase().indexOf(
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&filename=\&&);
&&&&&&&&&&&&&&&&&&&&&&&&if (fIndex != -1) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&fileFlag =
&&&&&&&&&&&&&&&&&&&&&&&&&&&&int fLastIndex = strBuff.toLowerCase().indexOf(
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\&&, fIndex + 10);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&fName = strBuff.substring(fIndex + 10, fLastIndex);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&fName = getFileName(fName);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&if (fName == null || fName.trim().length() == 0) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&fileFlag =
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&sis.readLine(buffs, 0, buffs.length);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&sis.readLine(buffs, 0, buffs.length);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&sis.readLine(buffs, 0, buffs.length);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&}else{
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&fName = getFileNameByTime(fName);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&sis.readLine(buffs, 0, buffs.length);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&sis.readLine(buffs, 0, buffs.length);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&} else if (strBuff.startsWith(endBoundary)) {
&&&&&&&&&&&&&&&&&&&&if (name != null && name.trim().length() & 0) {
&&&&&&&&&&&&&&&&&&&&&&&&if (fileFlag) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&bos.flush();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&baos.close();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&bos.close();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&baos =
&&&&&&&&&&&&&&&&&&&&&&&&&&&&bos =
&&&&&&&&&&&&&&&&&&&&&&&&&&&&updFileArr.add(fName);
&&&&&&&&&&&&&&&&&&&&&&&&} else {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&Object obj = paramHt.get(name);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&ArrayList al = new ArrayList();
&&&&&&&&&&&&&&&&&&&&&&&&&&&&if (obj != null) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&al = (ArrayList)
&&&&&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&&&&&al.add(value);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&paramHt.put(name, al);
&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&} else {
&&&&&&&&&&&&&&&&&&&&if (fileFlag) {
&&&&&&&&&&&&&&&&&&&&&&&&if (baos == null && bos == null) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&tmpFile = new File(uploadPath + fName);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&baos = new FileOutputStream(tmpFile);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&bos = new BufferedOutputStream(baos);
&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&bos.write(buffs, 0, rtnPos);
&&&&&&&&&&&&&&&&&&&&&&&&baos.flush();
&&&&&&&&&&&&&&&&&&&&} else {
&&&&&&&&&&&&&&&&&&&&&&&&System.out.println(&test :& + value + &--& + strBuff);
&&&&&&&&&&&&&&&&&&&&&&&&value = value + strB
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
&&&&&&&&} catch (IOException e) {
&&&&&&&&&&&&status = 4;
&&&&private int preCheck() {
&&&&&&&&int errCode = 0;
&&&&&&&&if ( request == null )
&&&&&&&&&&&&return 1;
&&&&&&&&if ( uploadPath == null || uploadPath.trim().length() == 0 )
&&&&&&&&&&&&return 2;
&&&&&&&&else{
&&&&&&&&&&&&File tmpF = new File(uploadPath);
&&&&&&&&&&&&if (!tmpF.exists())
&&&&&&&&&&&&&&&&return 2;
&&&&&&&&String contentType = request.getContentType();
&&&&&&&&if ( contentType.indexOf(&multipart/form-data&) == -1 )
&&&&&&&&&&&&return 3;
&&&&&&&&return errC
&&&&public String getParameter(String name){
&&&&&&&&String value = &&;
&&&&&&&&if ( name == null || name.trim().length() == 0 )
&&&&&&&&&&&&
&&&&&&&&value = (paramHt.get(name) == null)?&&:(String)((ArrayList)paramHt.get(name)).get(0);
&&&&public String[] getParameters(String name){
&&&&&&&&if ( name == null || name.trim().length() == 0 )
&&&&&&&&&&&&
&&&&&&&&if ( paramHt.get(name) == null )
&&&&&&&&&&&&
&&&&&&&&ArrayList al = (ArrayList)paramHt.get(name);
&&&&&&&&String[] strArr = new String[al.size()];
&&&&&&&&for ( int i=0;i&al.size();i++ )
&&&&&&&&&&&&strArr[i] = (String)al.get(i);
&&&&&&&&return strA
&&&&public int getUpdFileSize(){
&&&&&&&&return updFileArr.size();
&&&&public String[] getUpdFileNames(){
&&&&&&&&String[] strArr = new String[updFileArr.size()];
&&&&&&&&for ( int i=0;i&updFileArr.size();i++ )
&&&&&&&&&&&&strArr[i] = (String)updFileArr.get(i);
&&&&&&&&return strA
&&&&private String getFileName(String input){
&&&&&&&&int fIndex = input.lastIndexOf(&\\&);
&&&&&&&&if (fIndex == -1) {
&&&&&&&&&&&&fIndex = input.lastIndexOf(&/&);
&&&&&&&&&&&&if (fIndex == -1) {
&&&&&&&&&&&&&&&&
&&&&&&&&&&&&}
&&&&&&&&}&
&&&&&&&&input = input.substring(fIndex + 1);
&&&&private String getFileNameByTime(String input){
&&&&&&&&int index = input.indexOf(&.&);
&&&&&&&&Date dt = new Date();
&&&&&&&&SimpleDateFormat sdf = new SimpleDateFormat(&yyyyMMddHHmmssSSS&);
&&&&&&&&return input.substring(0,index) + sdf.format(dt) + input.substring(index);
2.在Jsp页面中进行引用该Java类:
&&import=&com.vogoal.util.JspFileUpload&%&
&&& //初始化
&&& JspFileUpload jfu = new JspFileUpload();
&&& //设定request对象
&&& jfu.setRequest(request);
&&& //设定上传的文件路径
&&& jfu.setUploadPath(&C:\\&);
&&& //上传处理
&&& int rtn = jfu.process();
&&& //取得form中其他input控件参数的值
&&& String username = jfu.getParameter(&username&);
&&& //如果对应同一个参数有多个input控件,返回数组
&&& String[] usernameArr = jfu.getParameters(&username&);
&&& //取得上传的文件的名字
&&& String[] fileArr = jfu.getUpdFileNames();
&&& //取得上传文件的个数,这个方法有点鸡肋
&&& int fileNumber = jfu.getUpdFileSize();
//下面的是测试输出的代码。
//&&&&&& out.println(&parameter:& + username);
//&&&&&& out.println(&parameter size:& + usernameArr.length);
//&&&&&& out.println(&fileArr size:& + fileArr.length);
//&&&&&& if (fileArr.length & 0)
//&&&&&&&&&&&&& out.println(&fileArr 0:& + fileArr[0]);
第三点:struts2实现文件的上传和下载
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从下载。
第二步:把form表的enctype设置为:“multipart/form-data“,如下:
Java代码 public class UploadAction{&&
& private File uploadI //文件&&
& private String uploadImageContentT//文件的类型&&
& private String uploadImageFileN//文件的名称&&
& private S//书名&&
& private S//作者&&
& private String saveP//文件的保存位置&&
& //属性的getter/setter方法&&
& public String upload() throws Exception{&&
&&&&&&&&&&&& //实现上传代码,I/O操作完成&&
& return &uploadSuccess&;&&
复制代码注:一个表单里的文件域对应Action中三个属性,分别是文件,文件名,文件类型,命名是固定的,文件名必须表单中的文件域名称相同(uploadImage),文件名为:文件+FileName,文件类型:文件+ContentType。
第四步:将我们的上传Action配置到struts.xml中。
Java代码 &action name=&upload& class=&com.gqy.UploadAction&&&&
&&&&& &param name=&savePath&&/uploadFile&/param&&&
&&&&& &result&/success.jsp&/result&&&
&/action&&&
复制代码注:
指定上传文件的在服务器上的保存目录,需要在UploadAction中为定义savePath变量并为其添加相应的setter和getter方法,便于Struts2将/uploadFile值赋给savePath属性,即要想在UploadAction中使用savePath变量必须在UploadAction定义。
手动配置文件过滤类型
Java代码 &param name=&allowTypes&&&&
&&& image/bmp,image/png,image/gif,image/jpeg&&
复制代码手动配置文件大小限制
Java代码 &param name=&maximumSize& &1048576&/param&&&
复制代码使用Struts2的文件上传拦截器实现文件过滤
Struts2提供了一个文件上传的拦截器—fileUpload,通过配置该拦截器可以方便实现上传文件的过滤。
配置fileUpload拦截器时,可以为其指定两个参数:
 allowedTypes:指定允许上传的文件类型,多个文件类型之间以英文逗号(,)隔开。
 maximumSize:指定允许上传的文件大小,单位是字节。
提示:通过配置fileUpload拦截器,可以轻松的实现文过滤,当文件过滤失败后,系统自动转入input逻辑视图,因此必须为该Action配置名为input的逻辑视图,除此之外,还必须显示地为该Action配置defaultStack的拦截器引用。
使用Struts2的拦截器实现文件过滤配置如下:
使用Struts2的拦截器实现文件过滤配置如下:
Java代码 &action name=&uploadFileAction& class=&com.actions.UploadFileAction&&&&
&&&&&&&&& &interceptor-ref name=&defaultStack&&&&
&&&&&&&&&&&&& &!-- 配置允许上传的文件类型,多个用&,&分隔 --&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&& &param name=&fileUpload.allowedTypes&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&& image/bmp,image/png,image/gif,image/jpeg,image/jpg&&&
&&&&&&&&&&&&&&&&&&& ,image/x-png, image/pjpeg&&
&&&&&&&&&&&&& &/param&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&& &!-- 配置允许上传的文件大小,单位字节,本例为:1MB --&&&
&&&&&&&&&&&&& &param name=&fileUpload.maximumSize&&1048576&/param&&&
&&&&&&&&& &/interceptor-ref&&&
&&&&&&&&& &result name=&input&&/jsp/oneFileFileupload.jsp&/result&&&
&&&&&&&&& &result name=&success&&/jsp/result.jsp&/result&&&
&/action&&&
复制代码当用户上传失败后,需要有一定的提示信息。在Struts2中,使用&s:fielderror/&标签即可将错误提示信息输出到页面中。
注:要想使用Struts2错误提示信息,则上传文件的Action类,必须继承ActionSupport,否则Struts2不会提供输出错误提示信息功能。
我们可以配置资源文件(.properties)来保存输出给用户的信息。
struts.messages.eror.file.too.large:当上传文件大小超过设定的值时,Struts2将输出该key对应的提示信息。
struts.messages.error.content.type.not.allowed:当上传文件类型不符合设定的值时,Struts2将输出该key对应的提示信息。
struts.messages.error.uploading:当上传文件时出现未知错误时,Struts2将输出该key对应的提示信息。
我们还要将资源文件配置到struts.xml文件中,接下来看看我们的资源文件,已经包含中文了,得把它进行一下转换再配置到工程中。
在struts.xml中设定资源文件:
&constant name=&struts.custom.i18n.resources& value=&messages&/&或
&constant name=&struts.custom.i18n.resources& value=&messages_zh_CN&/&
用命令native2ascii& d:\messages.properties d:\messages_zh_CN.properties将原有的资源文件转换成支持中的。
注:保持国际化,资源文件的名称后缀为: *_zh_CN+文件扩展名的形式。
对于多个文件上传的原理同上,但是需要注意的是,多个文件域的name属性名必须相同,而且在Action中应该使用File [] 或者List&File&来接收。
个人觉得用这样的方式进行多个文件上传不是
Struts2进行文件下载
Struts2提供了stream结果类型,该结果类型专门用于支持文件下载的功能。当指定stream结果类型时,需要配置一个inputName参数,该参数指定了一个输入流,这个输入流是被下载文件的入口(即通过该入口才能实现文件以流的方式实现下载)。
实现文件下载的Action
Java代码 public class FileDownloadAction implements Action{&&
&& //该属性值在配置文件中指定,Struts2会自动进行注入(即赋值),需要为该属性提供setter和 getter方法&&
&& private String inputP//指定要下载的文件的完整路径(路径名+文件名)&&
&&&& * 实现下载的Action类应该提供一个返回InputStream实例的方法,该方法对应在&&&&&&&
&&&&&&& &result.../&里的inputName属性值为targetFile&
&& public InputStream getTargetFile() throws Exception{&&
&&&&& return& ServletActionContext.getServletContext().getResourceAsStream(inputPath);&&
&& //处理用户请求的execute方法,该方法返回success字符串&&
&& public String execute() throws Exception{&&
&&&&& return &success&;&&
复制代码对应Action在struts.xml文件中的配置
Java代码 &action name=&download& class=&com.FileDownloadAction&&
&& &!--指定被下载资源的位置--&
&&&&& &param name=&inputPath&&/uploadFile/demo.txt&/param&
&& &!--配置结果类型为stream的结果--&
&& &result name=&success& type=&stream&&
&&&&&& &!--指定下载文件的文件类型--&
&&&&&&&&& &param name=&contentType&&&/param&
&&&&&& &!--指定下载文件的文件位置--&
&&&&&&&&& &param name=&inputName&&targetFile&/param&
&&&&&& &!--指定下载文件的下载方式及下载时的保存文件名,filename保存时的文件名必须有扩展名,扩展名指示了下载类型的图标--&
&&&&&&&&& &param name=&contentDisposition&&
&&&&&&&&&&&&&&&filename=Struts2.txt
&&&&&&&&& &/param&
&&&&&& &!--指定下载文件的缓冲区大小--&
&&&&&&&&& &param name=&bufferSize&&4096&/param&
&& &/result&
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:473524次
积分:5645
积分:5645
排名:第3001名
原创:49篇
转载:75篇
评论:67条
(2)(1)(2)(1)(3)(11)(12)(4)(1)(10)(10)(12)(5)(59)(1)关于SpringMVC的文件上传
其实文件上传的原理都是一样的,基于SpringMVC的文件上传实现要比Struts2要来得简单许多。
好了,废话不多说,直接切入主题吧,关于上传原理不了解的朋友,可以轻戳上面2篇文章的链接。
1、万变不离其宗,要实现文件的上传需要对应的JAR包:
1、commons-fileupload-1.2.2.jar
2、commons-io-2.0.1.jar
2、要实现SpringMVC的文件上传,需要配置一下文件:
&1 & & &!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --&
&2 & & &bean id=&multipartResolver&
&3 & & & & class=&org.springframework.monsMultipartResolver&&
&4 & & & & &property name=&defaultEncoding& value=&UTF-8& /&
&5 & & & & &!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --&
&6 & & & & &property name=&maxUploadSize& value=&-1& /&
&7 & & &/bean&
&9 & & &!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --&
10 & & &!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --&
11 & & &bean id=&exceptionResolver&
12 & & & & class=&org.springframework.web.servlet.handler.SimpleMappingExceptionResolver&&
13 & & & & &property name=&exceptionMappings&&
14 & & & & & & &props&
15 & & & & & & & & &!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到XXX页面 --&
16 & & & & & & & & &prop
17 & & & & & & & & & & key=&org.springframework.web.multipart.MaxUploadSizeExceededException&&跳转XXX页面&/prop&
18 & & & & & & &/props&
19 & & & & &/property&
20 & & &/bean&
3、上传页面
&1 &%@ page language=&java& contentType=&text/ charset=UTF-8&
&2 & & pageEncoding=&UTF-8&%&
&4 & & String path = request.getContextPath();
&5 & & String basePath = request.getScheme() + &://&
&6 & & & & & & + request.getServerName() + &:& + request.getServerPort()
&7 & & & & & & + path + &/&;
10 &!DOCTYPE html PUBLIC &-//W3C//DTD HTML 4.01 Transitional//EN& &http://www.w3.org/TR/html4/loose.dtd&&
13 &meta http-equiv=&Content-Type& content=&text/ charset=UTF-8&&
14 &title&上传文件&/title&
15 &/head&
17 & & &form action=&&%=basePath%&upload.do& method=&post&
18 & & & & enctype=&multipart/form-data&&
19 & & & & &input type=&hidden& name=&tuzi& value=&tuzi&&
20 & & & & 上传文件:&input type=&file& name=&uploadfile&&
21 & & & & &&input type=&submit& value=&上传&&
22 & & &/form&
23 &/body&
24 &/html&
4、文件处理类:
&1 package lcw.
&3 import java.io.F
&4 import java.io.IOE
&6 import javax.servlet.http.HttpServletR
&8 import mons.io.FileU
&9 import org.springframework.stereotype.C
10 import org.springframework.web.bind.annotation.RequestM
11 import org.springframework.web.bind.annotation.RequestP
12 import org.springframework.monsMultipartF
16 &* 文件上传处理类
19 @Controller
20 public class FileController {
22 & & //单文件上传
23 & & @RequestMapping(value = &/upload.do&)
24 & & public String queryFileData(
25 & & & & & & @RequestParam(&uploadfile&) CommonsMultipartFile file,
26 & & & & & & HttpServletRequest request) {
27 & & & & // MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
28 & & & & if (!file.isEmpty()) {
29 & & & & & & String type = file.getOriginalFilename().substring(
30 & & & & & & & & & & file.getOriginalFilename().indexOf(&.&));// 取文件格式后缀名
31 & & & & & & String filename = System.currentTimeMillis() +// 取当前时间戳作为文件名
32 & & & & & & String path = request.getSession().getServletContext()
33 & & & & & & & & & & .getRealPath(&/upload/& + filename);// 存放位置
34 & & & & & & File destFile = new File(path);
35 & & & & & & try {
36 & & & & & & & & // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
37 & & & & & & & & FileUtils
38 & & & & & & & & & & & & .copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
39 & & & & & & } catch (IOException e) {
40 & & & & & & & & e.printStackTrace();
41 & & & & & & }
42 & & & & & & return &redirect:upload_ok.&;
43 & & & & } else {
44 & & & & & & return &redirect:upload_error.jsp&;
45 & & & & }
6、再来看下关于多文件上传,其实原理还是一样,只不过是把CommonsMultipartFile类对象换成一个数组,然后用一个for循环去遍历这个数组,并分别存入。
&1 package lcw.
&3 import java.io.F
&4 import java.io.IOE
&6 import javax.servlet.http.HttpServletR
&8 import mons.io.FileU
&9 import org.springframework.stereotype.C
10 import org.springframework.web.bind.annotation.RequestM
11 import org.springframework.web.bind.annotation.RequestP
12 import org.springframework.monsMultipartF
16 &* 文件上传处理类
19 @Controller
20 public class FileController {
22 & & //单文件上传
23 & & @RequestMapping(value = &/upload.do&)
24 & & public String queryFileData(
25 & & & & & & @RequestParam(&uploadfile&) CommonsMultipartFile file,
26 & & & & & & HttpServletRequest request) {
27 & & & & // MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
28 & & & & if (!file.isEmpty()) {
29 & & & & & & String type = file.getOriginalFilename().substring(
30 & & & & & & & & & & file.getOriginalFilename().indexOf(&.&));// 取文件格式后缀名
31 & & & & & & String filename = System.currentTimeMillis() +// 取当前时间戳作为文件名
32 & & & & & & String path = request.getSession().getServletContext()
33 & & & & & & & & & & .getRealPath(&/upload/& + filename);// 存放位置
34 & & & & & & File destFile = new File(path);
35 & & & & & & try {
36 & & & & & & & & // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
37 & & & & & & & & FileUtils
38 & & & & & & & & & & & & .copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
39 & & & & & & } catch (IOException e) {
40 & & & & & & & & e.printStackTrace();
41 & & & & & & }
42 & & & & & & return &redirect:upload_ok.jsp&;
43 & & & & } else {
44 & & & & & & return &redirect:upload_error.jsp&;
45 & & & & }
48 & & //多文件上传
49 & & @RequestMapping(value = &/uploads.do&)
50 & & public String queryFileDatas(
51 & & & & & & @RequestParam(&uploadfile&) CommonsMultipartFile[] files,
52 & & & & & & HttpServletRequest request) {
53 & & & & if (files != null) {
54 & & & & & & for (int i = 0; i & files. i++) {
55 & & & & & & & & String type = files[i].getOriginalFilename().substring(
56 & & & & & & & & & & & & files[i].getOriginalFilename().indexOf(&.&));// 取文件格式后缀名
57 & & & & & & & & String filename = System.currentTimeMillis() +// 取当前时间戳作为文件名
58 & & & & & & & & String path = request.getSession().getServletContext()
59 & & & & & & & & & & & & .getRealPath(&/upload/& + filename);// 存放位置
60 & & & & & & & & File destFile = new File(path);
61 & & & & & & & & try {
62 & & & & & & & & & & FileUtils.copyInputStreamToFile(files[i].getInputStream(),
63 & & & & & & & & & & & & & & destFile);// 复制临时文件到指定目录下
64 & & & & & & & & } catch (IOException e) {
65 & & & & & & & & & & e.printStackTrace();
66 & & & & & & & & }
67 & & & & & & }
68 & & & & & & return &redirect:upload_ok.jsp&;
69 & & & & } else {
70 & & & & & & return &redirect:upload_error.jsp&;
71 & & & & }
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'}

我要回帖

更多关于 multipartfile 类型 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信