我使用GWT开发Web应用程序,我正在尝试上传文件。我的servlet运行正常。
但是当我使用DiskFileItemFactory()时,它给了我错误。
如果有人可以更正我的代码或告诉代码中缺少什么。
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
FileItem uploadItem = getFileItem(request);
if (uploadItem == null) {
response.getWriter().write("NO-SCRIPT-DATA");
return;
}
byte[] fileContents = uploadItem.get();
//TODO: add code to process file contents here. We will just print
response.getWriter().write(new String(fileContents));
}
private FileItem getFileItem(HttpServletRequest request) {
// TODO Auto-generated method stub
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (!item.isFormField()
&& "uploadForm".equals(item.getFieldName())) {
return item;
}
}
} catch (FileUploadException e) {
return null;
}
return null;
}
ERROR
java.lang.NoClassDefFoundError: java.rmi.server.UID is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
at org.apache.commons.fileupload.disk.DiskFileItem.<clinit>(DiskFileItem.java:109)
at org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:199)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:361)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at com.server.FileUpload.getFileItem(FileUpload.java:101)
at com.server.FileUpload.doPost(FileUpload.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
编辑:工作代码
try {
ServletFileUpload upload = new ServletFileUpload();
response.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName() + " " +item);
} else{
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
response.getOutputStream().write(buffer, 0, len);
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:3)
您无法在GAE中使用RMI - 如果您想要类似的内容,请查看this question。
但是从您的代码来看,您似乎根本不需要使用RMI - 为什么要使用它?你不是只是将它处理并存储在某个地方吗?
如果要存储大文件(最多32MB),请使用Blobstore API。
如果您知道自己只有<1MB的文件,则可以使用JDO / JPA和包含Entity的普通Blob存储它们 - 此选项也可让您轻松预存 - 处理数据。