您的位置:首页 > 其它

文件下载

2015-07-28 17:51 239 查看
本来以为简简单单的文件下载,会很快做完,结果中间出了几个小问题。

中文文件名乱码

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

}

[/code]对于问题2,只需要将空格去掉就Ok了,简单的字符替换,如下:

//去掉空格,否则ff下空格后的内容都会丢失

String fileName=fileInfo.getFileName().replace(" ","");

[/code]完整版代码如下:

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

    }

}

}

[/code]

来自为知笔记(Wiz)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: