您的位置:首页 > 编程语言 > Java开发

基于springMvc框架下的文件下载

2017-03-06 11:00 211 查看
/**

 * 文件下载

 * @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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: