利用MultipartFile实现文件上传功能
在java中上传文件似乎总有点麻烦,没.net那么简单,记得最开始的时候用smartUpload实现文件上传,最近在工作中使用spring的MultipartFile实现文件上传,感觉挺简单,在这里和大家分享一下。
一.主要有两个java类,和一般的servlet放在一起即可.
1.FileUploadBean.java
packagechb.demo.web;
importorg.springframework.web.multipart.MultipartFile;
/**
*@authorchb
*
*/
publicclassFileUploadBean{
privateMultipartFilefile;
publicvoidsetFile(MultipartFilefile){
this.file=file;
}
publicMultipartFilegetFile(){
returnfile;
}
}
2.FileUploadController.java
packagechb.demo.web;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.validation.BindException;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.SimpleFormController;
/**
*@authorchb
*
*/
publicclassFileUploadControllerextendsSimpleFormController{
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,利用springmvc模式,大家应该都很熟悉了
chb org.springframework.web.servlet.DispatcherServlet 1 chb *.do
2.chb-servlet.xml,这里要配置映射,并可以设定最大可上传文件的大小
action index fileUploadController
三.设定jsp页面
上传文件:
ok,现在就可以上传文件了,挺简单吧?这里我只列出了基本步骤,至于具体的操作(比如中文问题)可能就需要大家自己再完善完善了.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。