0

这是我用来下载图像并保存的代码。任何人都可以建议我还需要做什么或我在这里错过了什么吗?提前致谢

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    BufferedWriter writer = null;
    InputStream in = new BufferedInputStream(request.getInputStream());
            try {                       
        byte[] buffer = new byte[100000];
        int n = -1;
        while ((n = in.read(buffer)) >= 0) {
            out.write(buffer, 0, n); // used for image
        }
        out.close();
        byte[] res = out.toByteArray();
        out.flush();
        FileOutputStream fos = new FileOutputStream("D://"+ new SimpleDateFormat("yyyyMMdd_HHmmssss").format(Calendar.getInstance().getTime()) +".jpg");
        fos.write(res);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
4

2 回答 2

0

我找到了基于 Multipart/form-data 的问题的替代解决方案,因为服务器应该能够处理 mulipart/form-data。为此我必须拥有

private static final MultipartConfigElement MULTI_PART_CONFIG = new MultipartConfigElement(
        System.getProperty("java.io.tmpdir"));

处理程序内部

if (request.getContentType() != null
            && request.getContentType().startsWith("multipart/form-data")) {
        baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT,
                MULTI_PART_CONFIG);
    }

在handle方法中,我们可以从请求中获取文件,如下所示

@Override
public void handle(String target, Request baseRequest,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (request.getContentType() != null
            && request.getContentType().startsWith("multipart/form-data")) {
        baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT,
                MULTI_PART_CONFIG);
    }
    // response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    baseRequest.setHandled(true);


        final FileOutputStream output = new FileOutputStream("D:\\Dir\\"+ request.getParameter("imageName") + ".jpg");
        IOUtils.copy(request.getPart("file").getInputStream(), output);
        output.close();


}

这里是来自 apache commons-io jar 文件的 IOUtils

于 2013-07-26T11:14:02.723 回答
0

可能是因为您没有设置响应头和内容类型。试试这个

 protected void doGet( HttpServletRequest request,HttpServletResponse response)
    {
        try {
            Path path = Paths.get("c:\\test.jpg");
            response.setHeader("Content-Length", ""+Files.size(path));
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "attachment; filename=\""+path.getFileName()+"\";");
            ServletOutputStream outputStream;
            outputStream = response.getOutputStream();
            byte[] data = Files.readAllBytes(path);
            outputStream.write(data);
        } catch (IOException ex) {ex.printStackTrace();}
    }
于 2013-07-25T06:45:43.437 回答