文件下载
本来以为简简单单的文件下载,会很快做完,结果中间出了几个小问题。
- 中文文件名乱码
- firefox下载的文件扩展名丢失
既然问题出了,就得解决。一番百度,得如:
- 如果是IE,则需要用对中文编码
- 如果是ff、chrome,则需要转成ISO8859-1
- ff会将空格之后的文本抛弃
既然知道了原因,那就好解决了。
对于问题1,代码如下:
//解决中文乱码的问题try {if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE")>0){fileName=URLEncoder.encode(fileName, "UTF-8");}else {fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");}System.out.println("fileName:"+fileName);response.setHeader("Content-Disposition","attachment;filename="+fileName);} catch (UnsupportedEncodingException e) {e.printStackTrace();}
对于问题2,只需要将空格去掉就Ok了,简单的字符替换,如下:
//去掉空格,否则ff下空格后的内容都会丢失String fileName=fileInfo.getFileName().replace(" ","");
完整版代码如下:
String filePath= Config.getProperty("filePath")+ File.separator+PubConst.SRCFILECATALOG + fileInfo.getFilePath()+fileInfo.getFileId()+"."+fileInfo.getSuffixName();//设置响应头信息response.reset();//解决中文乱码的问题//去掉空格,否则ff下空格后的内容都会丢失String fileName=fileInfo.getFileName().replace(" ","");try {if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE")>0){fileName=URLEncoder.encode(fileName, "UTF-8");}else {fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");}System.out.println("fileName:"+fileName);response.setHeader("Content-Disposition","attachment;filename="+fileName);} catch (UnsupportedEncodingException e) {e.printStackTrace();}//将文件写入到返回流中InputStream is=null;OutputStream os=null;try {is=new FileInputStream(filePath);os=response.getOutputStream();byte[] buffer=new byte[1024];int length=0;while ((length=is.read(buffer))>0){os.write(buffer,0,length);}DbBuss_FileInfo.addDownloadCount(fileInfo.getFileId());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}if(os!=null){try {os.close();} catch (IOException e) {e.printStackTrace();}}}

浙公网安备 33010602011771号