1、首先导入jar包:
2、然后,在applicatincontext.xml中添加上传和下载的配置文件,如下:
<!-- 文件上传的配置 -->
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
<!-- 指定所上传文件的总大小不能超过200kb。注意maxuploadsize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxuploadsize" value="200000"/>
</bean>
<!-- 该异常是springmvc在检查上传的文件信息时抛出来的,而且此时还没有进入到controller方法中 -->
<bean id="exceptionresolver" class="org.springframework.web.servlet.handler.simplemappingexceptionresolver">
<property name="exceptionmappings">
<props>
<!-- 遇到maxuploadsizeexceededexception异常时,自动跳转到webcontent目录下的error.jsp页面 -->
<prop key="org.springframework.web.multipart.maxuploadsizeexceededexception">error</prop>
</props>
</property>
</bean>
3、好了,最基础的配置就好了,接下来jsp页面:upload.jsp
1 <form action="upload.do" method="post" enctype="multipart/form-data">
2 文件1: <input type="file" name="myfiles"/><br/>
3 文件2: <input type="file" name="myfiles"/><br/>
4 文件3: <input type="file" name="myfiles"/><br/>
5 <input type="submit" value="上传">
6 </form>
4、controller中对应的java代码:
@requestmapping("/upload.do")
public string upload(@requestparam multipartfile[] myfiles,httpservletrequest request) throws ioexception {
for(multipartfile file : myfiles){
//此处multipartfile[]表明是多文件,如果是单文件multipartfile就行了
if(file.isempty()){
system.out.println("文件未上传!");
}
else{
//得到上传的文件名
string filename = file.getoriginalfilename();
//得到服务器项目发布运行所在地址
string path1 = request.getsession().getservletcontext().getrealpath("image")+file.separator;
// 此处未使用uuid来生成唯一标识,用日期做为标识
string path = path1+ new simpledateformat("yyyymmddhhmmss").format(new date())+ filename;
//查看文件上传路径,方便查找
system.out.println(path);
//把文件上传至path的路径
file localfile = new file(path);
file.transferto(localfile);
}
}
return "uploadsuccess";
}
这样就可以把网页上选择的图片上传上去了.
下载成功了!
5、文件下载download.jsp:此处为了测试,我直接把用户名当作参数传过去:
<a href="download.do?filename=2016082312271111111.jpg">下载</a>
6、controller:
@requestmapping("/download")
public string download(string filename, httpservletrequest request,
httpservletresponse response) {
response.setcharacterencoding("utf-8");
response.setcontenttype("multipart/form-data");
response.setheader("content-disposition", "attachment;filename="
+ filename);
try {
string path = request.getsession().getservletcontext().getrealpath
("image")+file.separator;
inputstream inputstream = new fileinputstream(new file(path
+ filename));
outputstream os = response.getoutputstream();
byte[] b = new byte[2048];
int length;
while ((length = inputstream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputstream.close();
} catch (filenotfoundexception e) {
e.printstacktrace();
} catch (ioexception e) {
e.printstacktrace();
}
// 返回值要注意,要不然就出现下面这句错误!
//java+getoutputstream() has already been called for this response
return null;
}
以上就是springmvc文件上传和下载 的详细内容。