Java file stream and download the file does not exist

Do file download function, the general use of the form to download the file stream,

If the source file does not exist, you might not prompt the download page, or a blank

After the user may operate at a loss, then how friendly and prompt it?

There are two conceivable

1. You can try to download a name: the file does not exist .txt document, which can also add descriptive information to ensure that each file can be downloaded to avoid the user does not respond to the situation.

2. Background output prompted a JavaScript script file does not exist or has been deleted.

Directly on the code

Only the front to give a hyperlink

< A the href = "$ {} pageContext.request.contextPath / Receipt / downloads? Routine popular fileName = .jpg" > Routine popular .jpg </ A >

Back-end controller code

/**
     * Download invoices
     * @param request
     * @return
     */
    @RequestMapping(value = "/receipt/download",method = RequestMethod.GET)
    public void downloadReceipt(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 获得要下载的文件的名称
        String fileName = request.getParameter("fileName");
        File file = new File(receiptPath + fileName);
        if(file.exists()){
            try {

                String userAgent = request.getHeader("User-Agent");
                if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                    //IE浏览器处理
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                } The else {
                     // non IE browser process: 
                    fileName = new new String (fileName.getBytes ( "UTF-. 8"), "the ISO-8859-1" );
                }

                // Download the file as a stream. 
                = InputStream the InputStream new new BufferedInputStream ( new new the FileInputStream (File));
                 byte [] Buffer = new new  byte [inputStream.available ()];
                inputStream.read(buffer);
                inputStream.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName));
                response.addHeader("Content-Length", "" + file.length());
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                outputStream.write(buffer);
                outputStream.flush();
                outputStream.close();
            }catch (IOException ex) {
                log.error ( "Error downloading file:" + EX);
            }
        }else{
            try {
                response.setContentType("text/html; charset=UTF-8"); //转码
                PrintWriter out = response.getWriter();
                out.flush();
                out.println("<script defer='defer' type='text/javascript'>");
                out.println ( "Alert ( 'file does not exist or has been deleted!');" );
                out.println("window.location='/AnnualStatistics/downloadList';");
                out.println("</script>");
            } catch (IOException e) {
                log.error ( "Download File Error:" + E);
            }
        }
    }

effect

Guess you like

Origin www.cnblogs.com/liuxiutianxia/p/11139575.html