我正在尝试对我的应用程序进行编程以上传图像,然后将它们存储在一个文件夹中。它打印出文件的详细信息,但不将其存储到文件夹中。我正在关注此处的用户指南和答案,但我仍然不知道我做错了什么?
import java.io.File;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadAvatarCommand implements Command {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) {
DiskFileItemFactory factory = new DiskFileItemFactory();
String contextRoot = request.getServletContext().getRealPath("/");
factory.setRepository(new File(contextRoot + "WEB-INF/tmp"));
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// Process form file field (input type="file").
System.out.println("Field name: " + item.getFieldName());
System.out.println("File name: " + item.getName());
System.out.println("File size: " + item.getSize());
System.out.println("File type: " + item.getContentType());
String fileName = item.getName();
try {
File saveFile = new File(fileName);
saveFile.createNewFile();
item.write(saveFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
try {
throw new ServletException("Cannot parse multipart request.", e);
} catch (ServletException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return "profile";
}
}