Spring MVC 文件下载
首先在springmvc.xml配置上传
<bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1024000"/>
</bean>
然后写下载文件的Controller
@Controller
@RequestMapping("download")
public class DownloadController {
/**
* 下载文件
* @param fileName
* @param requset
* @param response
*/
@RequestMapping("download")
public String download(String fileName,HttpServletRequest requset,HttpServletResponse response){
response.setContentType("text/html;charset=utf-8");
try {
requset.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedInputStream bis=null;
BufferedOutputStream bio=null;
String ctxPath = requset.getSession().getServletContext().getRealPath("/")+"upload/";
String downloadPath=ctxPath+fileName;
System.out.println(downloadPath);
try {
long fileLength = new File(downloadPath).length();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Length", fileLength+"");
response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes(),"iso8859-1"));
bis = new BufferedInputStream(new FileInputStream(downloadPath));
bio = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while((bytesRead = bis.read(buff, 0, buff.length)) != -1){
bio.write(buff, 0 , bytesRead );
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bio!=null){
try {
bio.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
}