我正在尝试为GwtUpload库实现基本示例,如here所示。
在我的服务器代码中,我收到以下错误:
异常java.lang.ClassCastException:org.apache.commons.fileupload.disk.DiskFileItem无法强制转换为org.apache.commons.fileupload.FileItem
我无法弄清楚为什么会这样。 DiskFileItem是FileItem的子类,应该可以工作。我已经在调试器中逐步完成并确认这两个类是它们看起来的样子,但是赋值失败了。
更奇怪的是,当我尝试在监视窗口中调用FileItem方法时,我没有问题,但如果我尝试在代码中访问它们,我就会收到错误。
这是我的Servlet代码:
public class GwtUploadServlet extends UploadAction
{
private static final long serialVersionUID = 1L;
/**
* Maintain a list with received files and their content types.
*/
Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();
/**
* Maintain a list with received files.
*/
Hashtable<String, File> receivedFiles = new Hashtable<String, File>();
/**
* Override executeAction to save the received files in a custom place and
* delete this items from session.
*/
@Override
public String executeAction(HttpServletRequest request,
List<FileItem> sessionFiles) throws UploadActionException
{
String response = "";
int cont = 0;
for ( int i = 0 ; i < sessionFiles.size(); i++ )
{
if (false == sessionFiles.get(i).isFormField())
{
cont++;
try
{
// / Create a temporary file placed in the default system
// temp folder
File file = File.createTempFile("upload-", ".bin");
sessionFiles.get(i).write(file);
// / Save a list with the received files
receivedFiles.put(sessionFiles.get(i).getFieldName(), file);
receivedContentTypes.put(sessionFiles.get(i).getFieldName(),
sessionFiles.get(i).getContentType());
// / Send a customized message to the client.
response += "File saved as " + file.getAbsolutePath();
}
catch (Exception e)
{
throw new UploadActionException(e);
}
}
}
// / Remove files from session because we have a copy of them
removeSessionFileItems(request);
// / Send your customized message to the client.
return response;
}
/**
* Get the content of an uploaded file.
*/
@Override
public void getUploadedFile(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
String fieldName = request.getParameter(PARAM_SHOW);
File f = receivedFiles.get(fieldName);
if (f != null)
{
response.setContentType(receivedContentTypes.get(fieldName));
FileInputStream is = new FileInputStream(f);
copyFromInputStreamToOutputStream(is, response.getOutputStream());
}
else
{
renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
}
}
/**
* Remove a file when the user sends a delete request.
*/
@Override
public void removeItem(HttpServletRequest request, String fieldName)
throws UploadActionException
{
File file = receivedFiles.get(fieldName);
receivedFiles.remove(fieldName);
receivedContentTypes.remove(fieldName);
if (file != null)
{
file.delete();
}
}
}
答案 0 :(得分:5)
确保类路径上没有多个版本的commons-fileupload。