java文件下载代码

/**

    * 文件下载

    * @param url 下载路径

    * @param request 解析对象

    * @param response 响应对象

    * @return

    */

    @ResponseBody

@RequestMapping("/fileDownload")

public String fileDownload(@RequestParam("url")String url,HttpServletRequest request,HttpServletResponse response) {

    System.out.println(url);

    String message = "导入成功!";

    String flag = "1";//0:失败,1:成功

String data = "";

InputStream inStream = null;

BufferedInputStream bfin = null;

BufferedOutputStream bfout = null;

try{

File file = new File(url);

if(!file.exists()){

throw new FileException() ;

}

int s = url.indexOf("_");

String sub = url.substring(s+1);

System.out.println(sub);

//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型   

            response.setContentType("multipart/form-data");   

            //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)   

            response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(sub, "UTF-8")); 


        inStream = new FileInputStream(url);//文件的存放路径

        bfin = new BufferedInputStream(inStream);

        bfout = new BufferedOutputStream(response.getOutputStream());

        byte[] b = new byte[1024];

        int len = 0;

        while ((len = bfin.read(b)) > 0) {

        bfout.write(b, 0, len);

        }

        bfout.flush();

} catch(FileException e){

System.out.println("文件下载失败!");

message = "文件已被删除或移除";

    flag = "0";

data = "{flag:" + flag + ",message:\"" + message +"\"}";

} catch (Exception e) {

e.printStackTrace();

System.out.println("文件下载失败!");

message = "下载失败";

    flag = "0";

data = "{flag:" + flag + ",message:\"" + message +"\"}";

}finally{

try {

inStream.close();

bfout.close();

bfin.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return data;

}

你可能感兴趣的:(java文件下载代码)