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

2020-07-02  本文已影响0人  lodtap

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

}

}

}

上一篇 下一篇

猜你喜欢

热点阅读