使用MultipartFile怎么实现一个文件上传功能
发布时间:-01-20 16:43:15
来源:亿速云
阅读:139
作者:Leah
使用MultipartFile怎么实现一个文件上传功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
一.主要有两个java类,和一般的servlet放在一起即可.
1.FileUploadBean.javapackagechb.demo.web;
importorg.springframework.web.multipart.MultipartFile;
/**
*@authorchb
*
*/
publicclassFileUploadBean{
privateMultipartFilefile;
publicvoidsetFile(MultipartFilefile){
this.file=file;
}
publicMultipartFilegetFile(){
returnfile;
}
}
2.FileUploadController.javapackagechb.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,利用spring mvc模式,大家应该都很熟悉了
chb
org.springframework.web.servlet.DispatcherServlet
1
chb
*.do
2.chb-servlet.xml,这里要配置映射,并可以设定最大可上传文件的大小<?xml version="1.0"encoding="UTF-8"?>
beansPUBLIC"-//SPRING//DTDBEAN//EN""/dtd/spring-beans.dtd">
action
index
fileUploadController
三.设定jsp页面
上传文件:
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。