上传处理
springmvc将上传文件封装在MultipartFile中,并且org.springframework.web.multipart.MultipartFiles接口提供了很多处理方法
使用jar包:
commons-fileupload.x.x.jar
commons-io.x.x.jar
spring中配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResovler">
<property name="MaxUploadSize" value="1000000" />
</bean>
Controller中使用Multipart接口提供的方法
一个很粗糙的小例子
前端使用
<form:form action="../uploadImage" method="post" enctype="multipart/form-data">
...
<input type="file" name="images[0]"/>
...
</form:form>
注: 包装类型参数绑定,name与Controller方法参数的属性对应。
下载处理
资源下载本质上是将资源以流的形式传输,所以web开发中就是把数据流发送至浏览器上。
基本操作
- 在Controller中使用HttpServletResponse
- Content-Type设置为文件内容类型
- 添加Content-Disposition的http相应标题,赋值为attachment; filename=filename
废话少说,简单例子
- 核心处理
以byte数组作为中间buffer,本地读入文件至buffer,然后输出至浏览器。输出钱需要对http response属性进行修改
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[bis.available];
response.setContentType(contentType);
response.addHeader("Content-Disposition", "attachment; filename=file-name");
OutputStram os = response.getOutputStream();
bis.read(buffer);
os.write(buffer);