基于springMvc框架下的文件下载

来源:互联网 发布:java安全框架权限管理 编辑:程序博客网 时间:2024/06/05 08:38

/**

 * 文件下载

 * @throws UnsupportedEncodingException

 */

@RequestMapping(value ="/download",method = RequestMethod.GET)

public String download(String fileName,HttpServletRequest request,HttpServletResponse response)throws UnsupportedEncodingException{

response.setCharacterEncoding("utf-8");

response.setContentType("multipart/form-data");

String str=new String(fileName.getBytes("ISO-8859-1"),"UTF-8");

response.setHeader("Content-Disposition","attachment;fileName="+str);

try {

String path=request.getSession().getServletContext().getRealPath("upload");//文件存放在这个目录下

InputStream inputStream=new FileInputStream(new File(path

+ File.separator+str));

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();

}

 

return null;

}






前台页面只需要个链接

<a href="${base}/product/download.jhtml?fileName=${product.fileName}"></a>

0 0
原创粉丝点击