如何在文件下载过程中覆盖现有文件,而不是创建新文件

时间:2018-10-25 17:10:57

标签: java gwt

我正在使用GWT进行文件上传,问题是如何覆盖现有文件(如果存在),而不是创建一个新文件,例如file(1).doc。这是我的服务器端代码。

protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try {
            String modelPath = AutoConstants.PREFIX + "/var/models/";

            File file = new File(modelPath + "/" + MODEL_NAME);

            if (file.exists()) {

                ServletOutputStream out = response.getOutputStream();
                DataInputStream in = new DataInputStream(new FileInputStream(
                        file));

                response.setHeader("Pragma", "public");
                response.setHeader("Cache-Control",
                        "must-revalidate, post-check=0, pre-check=0");
                response.setHeader("Content-Length",
                        String.valueOf(file.length()));
                response.setHeader("Content-Disposition",
                        "attachment; fileName=\"" + MODEL_NAME + "\"");

                int i = 0;
                int BUFSIZE = 8192;
                byte[] bbuf = new byte[BUFSIZE];
                while ((in != null) && ((i = in.read(bbuf)) != -1)) {
                    out.write(bbuf, 0, i);
                }

                in.close();
                out.flush();
            }

        } catch (Exception e) {
            logger.error("Exception.getModel", e);
            throw new ServletException(e.getMessage());
        }
    }

0 个答案:

没有答案