文件下载
-
访问资源时响应头如果没有设置Content-Disposition,浏览器默认按照inline方式进行处理 。
-
inline能显示就显示,不能显示就下载。
-
只需要修改响应头中
Context-Disposition=“attachment;filename=文件名”
。 -
attachment
下载,以附件形式下载。 -
filename=值,就是下载时显示的下载文件名。
-
导入apache文件上传的两个jar包
commons-fileupload、commons-io
。 -
下载普通文件:
/*html中:*/
<a href=”download?fileName=a.txt”>下载</a>
/*控制器中:*/
@RequestMapping(“/download”)
public void download(String fileName,HttpServletResponse res,HttpServletRequest req)throws exception{
//设置响应流中文件进行下载
res.setHeader(“Context-Disposition”,”attachment;filename=”+fileName)
//把二进制流放入到响应体中
ServletOutputStream os = res.getOutputStream();
// files是项目根目录下的一个文件夹,存放文件,fileName是files中的一个文件
//这个file可以是本地的一个文件,不是必须这么写
File file = new File(req.getServletContext().getRealPath(files,fileName);
Byte[] bytes=FileUtils.readFileToByteArray(file);
Os.write(bytes);
Os.flush();
Os.close();
}
- 下载excel文件:
<a href="download?uuid=a.xlsx">下载</a>
@RequestMapping("download")
public void download(String uuid, HttpServletResponse res) throws IOException {
//下载excel文件,设置格式
res.reset();
res.setCharacterEncoding("utf-8");
res.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//以xlsx格式下载
res.addHeader("Content-Type","application/force-download"); //出现下载保存窗口
res.addHeader("Content-disposition", "attachment;filename="+uuid);
ServletOutputStream os = res.getOutputStream();
String filepath = "D://"+uuid;
File file2 = new File(filepath);
byte[] by = FileUtils.readFileToByteArray(file2);
os.write(by);
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
文件上传
- 基于apach的
commons-fileupload
完成文件上传 - MultipartResovler,作用:把客户端上传的文件流转换成MultipartFile封装类;
- 通过MultipartFile封装类获取到文件流;
- 在<form>的
enctype
属性控制表单数据类型 - method=post最大限制为2GB
enctype取值 | 作用 |
---|---|
application/x-www-form-urlencoded | (默认值)普通表单数据(上传少量文字信息) |
text/plain | 大量文字数据的类型,邮件、论文 |
Multipart/form-data | 表单中包含二进制文件内容(上传文件必须设置) |
-
实现步骤
-
Jsp页面
<form action="upload" enctype="multipart/form-data" method="post">
选择文件:<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
- 在springmvc.xml中配置MultipartResolver解析器
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件的大小限制,单位为kb -->
<property name="maxUploadSize" value="100000"/>
</bean>
- 在控制器中MultipartFile file必须和<input type=“file” name=“file”>一致;
@RequestMapping("/upload")
public String upload(MultipartFile file, String name) throws IOException {
String filename = file.getOriginalFilename(); //获取上传的文件的名称
String suffix = filename.substring(filename.lastIndexOf(".")); //上传文件的后缀
UUID uuid = UUID.randomUUID(); //随机生成一个文件名
FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E:/"+uuid+suffix));
return "/index.jsp";
}