1,文件下载功能:
控制器层代码如下:
/*下载测试*/
@RequestMapping(value="downloadTest.do")
public void downloadTest(HttpServletResponse response, HttpServletRequest request){
log.info("下载测试, downloadTest.do,");
String str = "下载测试";
ServletOutputStream sos = null;
FileInputStream fis = null;
try {
sos = response.getOutputStream(); //得到网络输出流
//获取文件真实路径
String filePath = request.getSession().getServletContext().getRealPath("/web-inf/file/music/music1.mp3");
String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1); //获取文件名
response.setContentType("multipart/form-data"); //设置文件类型(自动)
response.setHeader("Content-Disposition", "attachment;fileName="+ fileName); //设置文件名
fis = new FileInputStream(filePath); //文件输入流
int len; //一次读取文件字节长度
byte[] bytes = new byte[1024]; //字节缓存区域
while((len = fis.read(bytes)) != -1){
sos.write(bytes, 0, len);
}
sos.flush(); //刷新输出流(确保所有字节都已经通过)
} catch (IOException e) {
e.printStackTrace();
} finally{ //关闭流
try {
sos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
页面标签:
<a class="btn btn-info" type="button" href="test/downloadTest.do">下载</a>
实现效果:
二,文件上传
前端标签如下,
<form enctype="multipart/form-data" action="test/upload.do" method="post">
<div class="row">
<div class="col-xs-4">
<input type="file" name="file" >
</div>
<div class="col-xs-4">
<input type="submit" class="btn btn-danger" value="上传文件">
</div>
</div>
</form>
注意: enctype=”multipart/form-data” 不能少
然后在 springmvc的配置文件中加入:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1000000"/>
</bean>
后台使用MultipartFile 类接收上传来的文件,
/*上传测试*/
@RequestMapping(value="upload.do")
public ModelAndView upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
Map<String, Object> json = new HashMap<String, Object>();
FileOutputStream fos = null;
try {
byte[] bytes = file.getBytes();
log.info("file-byte-lengerth: " + bytes.length);
String fileName = request.getServletContext().getRealPath("/web-inf/file/" + file.getOriginalFilename());
log.info("fileName: " + fileName);
fos = new FileOutputStream(fileName);
fos.write(bytes);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new ModelAndView(new JsonView(), json);
}