Java 文件是否附加在文件字段中?
我有以下代码:Java 文件是否附加在文件字段中?,java,servlets,file-upload,apache-commons-fileupload,Java,Servlets,File Upload,Apache Commons Fileupload,我有以下代码: 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()) { Stri
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"/>
该项从不为空
只需检查FileItemgetName文件名是否为空和/或FileItemgetSize文件大小是否等于0
在您的特定情况下,使用,将是:
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.
}
}
}
该项从不为空
只需检查FileItemgetName文件名是否为空和/或FileItemgetSize文件大小是否等于0
在您的特定情况下,使用,将是:
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.
}
}
}
您可以使用以下代码检查fileupload控件是否有任何值。filename是我的fileupload控件的名称
if ("filename".equals(item.getFieldName()) && item.getSize() > 0) {
// your code here
} else {
// Exception handling as no file chosen/attached
}
您可以使用以下代码检查fileupload控件是否有任何值。filename是我的fileupload控件的名称
if ("filename".equals(item.getFieldName()) && item.getSize() > 0) {
// your code here
} else {
// Exception handling as no file chosen/attached
}
你有合适的型号吗?有。enctype=多部分/表单数据您有正确的enctype吗?有。enctype=multipart/form data非常感谢。很久以来我一直在寻找答案,但我找不到答案。但是文件字段名是如何直接访问的呢?这只是符合多部分/表单数据编码规范。顺便说一句,在默认应用程序/x-www-form-urlencoded编码中也是如此,输入字段名称始终作为请求参数名称出现,但它们可以作为空字符串提交,这可以通过作为空字符串而不是空字符串提交的值来识别。非常感谢。很久以来我一直在寻找答案,但我找不到答案。但是文件字段名是如何直接访问的呢?这只是符合多部分/表单数据编码规范。顺便说一句,在默认应用程序/x-www-form-urlencoded编码中,输入字段名称始终作为请求参数名称出现,但它们可以作为空提交,这可以通过提交为空字符串而不是空字符串的值来识别。您可能希望格式化您的答案以区分代码和文本:您可以使用下面的代码检查您的fileupload controlfilename在我的案例中是否有任何错误value@Lincoln:当然可以。我将考虑这一建议。感谢you@BalusC我最近开始做一些旧版本的项目,所以现在我已经解决了这些问题。此外,由于声誉问题,我无法投票,我试图通过我的回答使代码看起来简短、简单和清晰。我完全同意你的回答。请把它看作是对你的答案的一种简化,因为所有的条件都在第一次看到它的时候产生了混乱。无论如何谢谢你!您可能需要格式化您的答案以区分代码和文本:您可以使用下面的代码检查您的fileupload controlfilename在我的案例中是否有任何value@Lincoln:当然可以。我将考虑这一建议。感谢you@BalusC我最近开始做一些旧版本的项目,所以现在我已经解决了这些问题。此外,由于声誉问题,我无法投票,我试图通过我的回答使代码看起来简短、简单和清晰。我完全同意你的回答。请把它看作是对你的答案的一种简化,因为所有的条件都在第一次看到它的时候产生了混乱。无论如何谢谢你!