简体   繁体   中英

How can I get info from a html form in JAVA without servlet?

I am uploading file by HTML form:

<form class="formulario" action="validatorKenken.cgi" method="GET">
                    <input type="file" name="xml" accept="*.xml"> <br/>
                    <input type="submit">   
</form>

Java file is called for CGI File which is called by the form. I need to save the file, which I am uploading, at server.

I have seen solutions using servlet but I have problems to compile it because the import javax.servlet is not exist.

I am using Java 1.7.0_101

Thank you!

The script will have the CONTENT_TYPE environment variable set to either application/x-www-form-urlencoded or multipart/form-data . The latter is usually used only for forms with <input type=file> controls. Either way, the request body will be in the standard input, which Java will inherit, along with all environment variables.

Since your form has a file field, the content type will be multipart/form-data . The body will contain a multipart MIME message.

Parsing a multipart MIME message is an order of magnitude easier if you use a JavaMail implementation, as you can make use of its MimeMultipart class, and its related classes:

Path saveDir = Paths.get("/home/enery93/Downloads");

// id or name attribute of HTML <input type='file'> element
String fileInputControlName = "file";

Path formDataFile = Files.createTempFile(null, null);
Files.copy(System.in, formDataFile, StandardCopyOption.REPLACE_EXISTING);

MimeMultipart formData = new MimeMultipart(
    new FileDataSource(formDataFile.toFile()));

int count = formData.getCount();
for (int i = 0; i < count; i++) {
    BodyPart part = formData.getBodyPart(i);

    // See HTML 4.01 spec, section 17.13.4 at
    // https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
    ContentDisposition disposition =
        new ContentDisposition(part.getDisposition());
    String name = disposition.getParameter("name");

    if (fileInputControlName.equals(name)) {
        Path saveFile = saveDir.resolve(part.getFileName());
        try (InputStream content = part.getInputStream()) {
            Files.copy(content, saveFile);
        }
        break;
    }
}

Files.delete(formDataFile);

As of this writing, a complete javax.mail.jar is available at http://java.net/projects/javamail/downloads/download/javax.mail.jar .

If you are unable or unwilling to use JavaMail, you'll have to parse the multipart content yourself, which is not pleasant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM