获取复选框的值以及上载文件

时间:2014-04-16 06:09:02

标签: java servlets file-upload

我试图使用commonsIO和Jar上传一个图像用于文件上传。但我面临的问题是我在表单上有两个复选框如下:

<div style="float:left">
  <input name="Mcheckbox" type="checkbox" value="Mobile"/>
  Mobile
</div>
<div style="float:right">
  <input name="Echechkbox" type="checkbox" value="Email"/>
  Email
</div>

然后浏览选项:

Upload Image : <INPUT TYPE="file" NAME="file" value="file"></input>

在我的servlet中我正在做这样的事情:

ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> files = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
Iterator it = files.iterator();

然后:

while (it.hasNext()) {
    FileItem fi = (FileItem) it.next();

    if (fi.isFormField()) {
        if (fieldname.compareTo("Mcheckbox") == 0) {

            System.out.println("checkbox value is " + fieldvalue);
            mymobilepass = fieldvalue;
        } else if (fieldname.compareTo("Echeckbox") == 0) {

            System.out.println("checkbox value is " + fieldvalue);
            myemailpass = fieldvalue;
        }

    } else {
        InputStream is = fi.getInputStream();

        FileOutputStream fos = new FileOutputStream(path + "\\" + fi.getName());
        int x = is.read();

        while (x >= 0) {
            fos.write((byte) x);
            x = is.read();
            //System.out.println("reading");

        }
    }
}

但每次myemailpass或mymobilepass的值都是null。可能是什么原因?永远不会执行if语句。为什么?请帮忙

2 个答案:

答案 0 :(得分:0)

尝试这种方式,

 DiskFileUpload upload = new DiskFileUpload();
        String Chk1= "";
        String Chk2= "";
        try {

            List<FileItem> files= upload.parseRequest(request);
            for (FileItem item : files) {
                if (item.isFormField()) {
                    if (item.getFieldName("Mcheckbox")) {
                       //do some thing here 
                    } 
                }

希望这会有所帮助!!

答案 1 :(得分:0)

问题是您没有在循环中设置fieldvalue

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> files = new ServletFileUpload(factory).parseRequest(request);

for (FileItem item : files) {
    if (item.isFormField()) {
        String fieldname = item.getFieldName();
        String fieldvalue = item.getString();
        if (fieldname.compareTo("Mcheckbox") == 0) {
            System.out.println("checkbox value is " + fieldvalue);
            mymobilepass = fieldvalue;
        } else if (fieldname.compareTo("Echeckbox") == 0) {
            System.out.println("checkbox value is " + fieldvalue);
            myemailpass = fieldvalue;
        }

    } else {
        InputStream is = item.getInputStream();

        FileOutputStream fos = new FileOutputStream(path + "\\" + fi.getName());
        int x = is.read();

        while (x >= 0) {
            fos.write((byte) x);
            x = is.read();
            //System.out.println("reading");

        }
    }
}