我正在使用apache commons-fileupload
上传文件。但是,我无法传递有关附件的更多信息。例如,用户希望在上传特定文件时添加附件信息。所以我将评论与附件一起发送。但是使用commons-fileupload,我只得到附件,但我无法得到评论。下面的代码是
<form action"taskcontroller" method="post" enctype="multipart/form-data">
<label for="filename_1">File: </label>
<input id="filename_1" type="file" name="filename_1" size="50"/><br/>
comments:<input type='text' name='comments' />
<input type="submit" value="upload" name="command" />
</form>
,下面的代码是处理请求,
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) { //ignore the form element
String fileName = item.getName();
// TODO filesize int is it ok?
int size = (int) item.getSize();
String root = "";//Set the root
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
item.write(uploadedFile); //write file to disk
}
}
}
但我无法获得评论信息......
答案 0 :(得分:1)
从字段isFormField()
中检查并检索字段getFieldName()
和getString()
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
String name;
String comment;
//Check for Form Field i.e. Comment field
if (item.isFormField()) {
name= item.getFieldName(); //Comment Field Name
comment = item.getString(); // Comment
}
//Check for attachment field
if (!item.isFormField()) { //ignore the form element
String fileName = item.getName();
// TODO filesize int is it ok?
int size = (int) item.getSize();
String root = "";//Set the root
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
item.write(uploadedFile); //write file to disk
}
}
}
答案 1 :(得分:0)
当您将文件上传到服务器时,会为照片添加唯一ID,并将评论存储在评论表中,并将照片存储在评论表中,以便唯一标识照片的评论。