zoukankan      html  css  js  c++  java
  • 文件下载时附件名乱码问题

    文件下载过程中,会出现中文名乱码或者文档名称中含有空格的,需要处理下,否则要么乱码,要么空格变成了“+”号,有点头疼。

    临时想到一种办法:

    即:

            //定义输出文件编码及类型和文件名 
       

    /**
    	 * 查看附件
    	 */
    	public String view() {
    		try {
    			Attachment newAttach = attachService.getAttachment(attach.getId());
    			if (attach != null) {
    				try {					
    					InputStream inStream = new FileInputStream(newAttach
    							.getFilePath());
    					this.getResponse().reset();
    					this.getResponse().setContentType("bin");
    					this.getResponse().addHeader(
    							"Content-Disposition",
    							"attachment; filename=""
    									+ URLEncoder.encode(newAttach.getName(),
    											"UTF-8").replace("+", "%20") + """);
    					// 循环取出流中的数据
    					byte[] b = new byte[512];
    					int len;
    					this.getResponse().getOutputStream().flush();
    					while ((len = inStream.read(b)) > 0) {
    						this.getResponse().getOutputStream().write(b, 0, len);
    					}
    					inStream.close();
    				} catch (FileNotFoundException e) {
    					//e.printStackTrace();
    					this.sendMessage("error");
    				} catch (IOException e) {
    					this.sendMessage("error");
    					//e.printStackTrace();
    				}
    			}
    		} catch (DAOException e) {
    			e.printStackTrace();
    			this.addActionMessage(e.getMessage());
    			return ERROR;
    		}
    		return null;
    	} 

    这样,在UrlEncode 之后, 将 "+" 替换成 "%20",因为浏览器将%20转换为空格,这样又空格再转换回来,就不影响下载的文件名称了,呵呵!

  • 相关阅读:
    android 多线程
    Uva 10881 Piotr’s Ants 蚂蚁
    LA 3708 Graveyard 墓地雕塑 NEERC 2006
    UVa 11300 Spreading the Wealth 分金币
    UVa 11729 Commando War 突击战
    UVa 11292 The Dragon of Loowater 勇者斗恶龙
    HDU 4162 Shape Number
    HDU 1869 六度分离
    HDU 1041 Computer Transformation
    利用可变参数函数清空多个数组
  • 原文地址:https://www.cnblogs.com/libaoting/p/fileUpload.html
Copyright © 2011-2022 走看看