将文件添加到表单中

时间:2017-02-02 03:33:08

标签: java html servlets

我想在servlet中向我的表单添加一个文件,而不会让用户向表单添加文件。当我用户时,我无法直接添加文件。出现一个选择框。有没有办法将文件与其他参数一起直接添加到表单中? 注意:每个表单的文件都在不断变化。

1 个答案:

答案 0 :(得分:0)

我基本上是尝试将打印命令发送到连接到网络的Xerox机器。当我使用以下代码时,它向我发送一个页面,告诉我需要使用支持框架的浏览器。 我在servlet中使用的代码是:

    File upFile = new File("path/to/the/file");
    try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String authStr= uname+":"+password;
            String encoding = Base64.encode(authStr.getBytes());
            HttpPost httppost = new HttpPost("printer's address/UPLPRT.cmd");
            httppost.setHeader("Authorization", "Basic " + encoding);
            FileBody uplFile = new FileBody(upFile);
            StringBody cpn = new StringBody(CPN, ContentType.TEXT_PLAIN);
            StringBody colt = new StringBody(COLT, ContentType.TEXT_PLAIN);
            StringBody dup = new StringBody(DUP, ContentType.TEXT_PLAIN);
            StringBody it = new StringBody(IT, ContentType.TEXT_PLAIN);
            StringBody siz = new StringBody(SIZ, ContentType.TEXT_PLAIN);
            StringBody med = new StringBody(MED, ContentType.TEXT_PLAIN);
            StringBody del = new StringBody(DEL, ContentType.TEXT_PLAIN);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                    .addPart("FILE",uplFile)
                    .addPart("CPN",cpn)
                    .addPart("COLT",colt)
                    .addPart("DUP", dup)
                    .addPart("IT", it)
                    .addPart("SIZ",siz)
                    .addPart("MED",med)
                    .addPart("DEL",del);
    HttpEntity reqEntity= builder.build();
            httppost.setEntity(reqEntity);
    CloseableHttpResponse resp = httpClient.execute(httppost);
    out.println(resp);
    } catch (Exception e) {
            out.println("Exception: Printer Not Responding");
            System.out.println(e);
    }