如何在java中获取表单文本框和图像值形式类型enctype =“multipart / form-data”

时间:2012-05-12 06:16:32

标签: java forms file-upload multipartform-data

如何在servlet加密为multipart / form-data时获取表单值。

<FORM name="filesForm" action="FileUpload" method="post" enctype="multipart/form-data">
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="file" name="filename">
</form>

如何在servlet的firstname,lastname和file值中获取这些值。

1 个答案:

答案 0 :(得分:3)

您可以使用apache commons fileupload:http://commons.apache.org/fileupload/

通常,您的代码类似于:

import org.apache.commons.fileupload.*;

...

DiskFileUpload upload = new DiskFileUpload();
List<FileItem> items = upload.parseRequest(request); // request is HttpServletRequest

// iterate through form fields
for(FileItem item:items) {
    if(item.isFormField()) { // text fields, etc...
        String fieldName = item.getFieldName();
        String value = item.getString();
    } else { // file fields
        item.write(new File("some/path"));
    }
}