【问题标题】:File is Attached or not in File field?文件是否附加在文件字段中?
【发布时间】:2013-04-23 14:14:41
【问题描述】:

我有以下代码:

if (formItems != null && formItems.size() > 0) {
    // iterates over form's fields
    for (FileItem item : formItems) {
        // processes only fields that are not form fields
        if (!item.isFormField()) {
            String fileName = new File(item.getName()).getName();
            String filePath = uploadPath + File.separator + fileName;
            File storeFile = new File(filePath);

            // saves the file on disk
            item.write(storeFile);
            session.setAttribute("image", fileName);
        }
        // processes only form fields
        else {
            String fieldname = item.getFieldName();
            String fieldvalue = item.getString();
            session.setAttribute(fieldname, fieldvalue);
        }
    }
}

我想先检查一个文件是否附加。如果附加,则仅上传文件。我试过这个:

if(item==null)

但这行不通。如何检查文件是否附加?我有一个文件字段:

<input type="file" name="image"/>

【问题讨论】:

  • 你有enctype吗?
  • 是的。 enctype="multipart/form-data"

标签: java servlets file-upload apache-commons-fileupload


【解决方案1】:

item 永远不是null

只需检查FileItem#getName()(文件名)是否为空和/或FileItem#getSize()(文件大小)是否等于0

在您的特定情况下,使用&lt;input type="file" name="image"/&gt;,将是:

if (!item.isFormField()) {
    if ("image".equals(item.getFieldName())) {
        if (item.getName() == null || item.getName().isEmpty()) {
            // No file was been selected.
        }

        if (item.getSize() == 0) {
            // No file was been selected, or it was an empty file.
        }
    }
}

【讨论】:

  • 非常感谢。我找了很长时间,但我无法得到答案。但是文件字段名是如何直接访问的呢?
  • 这只是符合multipart/form-data 编码规范。顺便说一下,默认application/x-www-form-urlencoded编码也是这种情况,输入字段名称始终作为请求参数名称存在,但它们可以作为空提交,这可以通过作为空字符串而不是@987654330提交的值来识别@.
【解决方案2】:

您可以使用以下代码来检查您的文件上传控件是否有任何值。 filename 是我的文件上传控件的名称

if ("filename".equals(item.getFieldName()) && item.getSize() > 0) {
    // your code here
} else {
    // Exception handling as no file chosen/attached
}

【讨论】:

  • 您可能需要格式化您的答案以区分代码和文本:“您可以使用以下代码检查您的文件上传控件(在我的情况下为“文件名”)是否具有任何价值”
  • @Lincoln:当然。会看这个建议的。谢谢
  • @BalusC 我最近开始处理一些旧版本的项目,所以现在解决了这些问题。此外,由于名誉问题无法投票,我试图通过我的回答使代码看起来简短、简单和清晰。
  • 我完全同意你的回答。请考虑将其简化为您的答案,因为所有条件在第一次查看时都会造成混乱。还是谢谢!
猜你喜欢
  • 2013-05-20
  • 2018-06-27
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多