标签:
本来以为简简单单的文件下载,会很快做完,结果中间出了几个小问题。
既然问题出了,就得解决。一番百度,得如:
既然知道了原因,那就好解决了。
对于问题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();
}
}
}
标签:
原文地址:http://www.cnblogs.com/xiaozhi123/p/4683641.html