美文网首页
2020-07-02 java后端文件下载

2020-07-02 java后端文件下载

作者: lodtap | 来源:发表于2020-07-02 17:00 被阅读0次

    @RequestMapping(value="/getfile")

    public void download(HttpServletResponse response,HttpServletRequest request) {

    String path = request.getParameter("path");

    File file = new File(path);

    InputStream is = null;

    OutputStream out = null;

    try {

    response.reset();

    response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(tfile.getFilename(), "UTF-8"));

    response.addHeader("Content-Length", "" + file.length());

    response.setContentType("application/octet-stream; charset=UTF-8");

    //设置跨域

    response.setHeader("Access-Control-Allow-Origin","*");

    response.setHeader("Access-Control-Allow-Credentials", "true");

    response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PATCH,PUT");

    response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,x-requested-with,X-Custom-Header," +"Content-Type,Accept,Authorization");

            String method01 = request.getMethod();

            if ("OPTIONS".equalsIgnoreCase(method01)){

                response.setStatus(HttpServletResponse.SC_ACCEPTED);

            }

    is = new FileInputStream(file);

    out = response.getOutputStream();

    byte[] buffer = new byte[1024];

    int len = 0;

    while((len = is.read(buffer)) != -1) {

    out.write(buffer, 0, len);

    }

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    }catch(IOException e) {

    e.printStackTrace();

    }finally {

    try {

    if(is != null) {

    is.close();

    }

    if(out != null) {

    out.close();

    }

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    }

    相关文章

      网友评论

          本文标题:2020-07-02 java后端文件下载

          本文链接:https://www.haomeiwen.com/subject/tovrqktx.html