从服务器下载文件学习笔记

                String fileUrl = "/data/evap/download/data/20171030_test.txt";
String fileName;
String filePath = fileUrl;
try {
FileInputStream fis = new FileInputStream(fileUrl);
//取绝对路径的最后"/"之后的str
fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
//文件名按utf-8取出,并按ISO8859-1编码保证文件名不出现乱码
fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8"); 
File file = new File(filePath);
//如果文件不存在
if(!file.exists()){
   return "文件不存在";
}
//告诉浏览器输出内容为流
response.setContentType("application/octet-stream");
//设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream out = response.getOutputStream();

byte[] b = new byte[1024];
            int len;
            while((len=fis.read(b))!=-1){
                out.write(b, 0, len);
            }
            //关闭流
            fis.close();
            out.close();
            
            return "success";
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

你可能感兴趣的:(数据集文件上传支持下载)