利用MultipartFile实现文件上传

利用MultipartFile实现文件上传

在java中上传文件似乎总有点麻烦,没.net那么简单,记得最开始的时候用smartUpload实现文件上传,最近在工作中使用spring的MultipartFile实现文件上传,感觉挺简单,在这里和大家分享一下.

一.主要有两个java类,和一般的servlet放在一起即可.

1.FileUploadBean.java

package chb.demo.web;

import org.springframework.web.multipart.MultipartFile;

/***/ /**
*
@authorchb
*
*/

public class FileUploadBean ... {

privateMultipartFilefile;

publicvoidsetFile(MultipartFilefile)...{
this.file=file;
}


publicMultipartFilegetFile()...{
returnfile;
}

}

2.FileUploadController.java

package chb.demo.web;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

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.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;


/***/ /**
*
@authorchb
*
*/

public class FileUploadController extends SimpleFormController ... {

protectedModelAndViewonSubmit(
HttpServletRequestrequest,
HttpServletResponseresponse,
Objectcommand,
BindExceptionerrors)
...{

try
...{
//castthebean
FileUploadBeanbean=(FileUploadBean)command;

//let'sseeifthere'scontentthere
MultipartFilefile=bean.getFile();

if(file==null)...{
thrownewException("上传失败:文件为�空");
}

if(file.getSize()>10000000)
...{
thrownewException("上传失败:文件大小不能超过10M");
}

//得到文件�名
Stringfilename=file.getOriginalFilename();

if(file.getSize()>0)...{
try...{
SaveFileFromInputStream(file.getInputStream(),
"D:/",filename);
}
catch(IOExceptione)...{
System.out.println(e.getMessage());
returnnull;
}

}

else...{
thrownewException("上传失败:上传文件不能为�空");
}

//well,let'sdonothingwiththebeanfornowandreturn:
try...{
returnsuper.onSubmit(request,response,command,errors);

}
catch(Exceptione)...{
System.out.println(e.getMessage());
returnnull;
}

}

catch(Exceptionex)
...{
System.out.println(ex.getMessage());
returnnull;
}

}


/***//**保存文件
*
@paramstream
*
@parampath
*
@paramfilename
*
@throwsIOException
*/

publicvoidSaveFileFromInputStream(InputStreamstream,Stringpath,Stringfilename)throwsIOException
...{
FileOutputStreamfs
=newFileOutputStream(path+"/"+filename);
byte[]buffer=newbyte[1024*1024];
intbytesum=0;
intbyteread=0;
while((byteread=stream.read(buffer))!=-1)
...{
bytesum
+=byteread;
fs.write(buffer,
0,byteread);
fs.flush();
}

fs.close();
stream.close();
}

}


二.配置文件中如下配置:

1.web.xml,利用spring mvc模式,大家应该都很熟悉了

< servlet >
< servlet-name > chb </ servlet-name >
< servlet-class > org.springframework.web.servlet.DispatcherServlet </ servlet-class >
< load-on-startup > 1 </ load-on-startup >
</ servlet >

< servlet-mapping >
< servlet-name > chb </ servlet-name >
< url-pattern > *.do </ url-pattern >
</ servlet-mapping >

2.chb-servlet.xml,这里要配置映射,并可以设定最大可上传文件的大小

<? xmlversion="1.0"encoding="UTF-8" ?>
<! DOCTYPEbeansPUBLIC"-//SPRING//DTDBEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
<!-- Multi-Action用来标识method的变量名定义 -->
< bean id ="methodNameResolver" class ="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver" >
< property name ="paramName" >
< value > action </ value >
</ property >
< property name ="defaultMethodName" >
< value > index </ value >
</ property >
</ bean >

< bean id ="multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- oneofthepropertiesavailable;themaximumfilesizeinbytes -->
< property name ="maxUploadSize" value ="10000000" />
</ bean >


< bean id ="handlerMapping" class ="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
< property name ="mappings" >
< props >
< prop key ="/upload.do" > fileUploadController </ prop >
</ props >
</ property >
</ bean >

< bean id ="fileUploadController" class ="chb.demo.web.FileUploadController" >
< property name ="commandClass" value ="chb.demo.web.FileUploadBean" />
<!-- 上传失败时跳转页面 -->
< property name ="formView" value ="/user/err.jsp" />
<!-- 上传成功时跳转页面 -->
< property name ="successView" value ="/user/confirmation.jsp" />
</ bean >
</ beans >

三.设定jsp页面

< form id ="form1" method ="post" action ="upload.do" enctype ="multipart/form-data" >
< tr >
< td width ="25%" align ="right" > 上传文件: </ td >
< td >< input id ="file" type ="file" NAME ="file" style ="width:300px;" ></ td >
</ tr >
< tr align ="center" valign ="middle" >
< td height ="60" colspan ="2" >< input type ="submit" ID ="BtnOK" value ="确认上传" ></ td >
</ tr >
</ form >

ok,现在就可以上传文件了,挺简单吧?这里我只列出了基本步骤,至于具体的操作(比如中文问题)可能就需要大家自己再完善完善了.

你可能感兴趣的:(MultipartFile)