我已经为此工作了2天,我终于放弃了,并在这里问。我希望能够将(文本)文件上传到PC。我正在进一步研究的这个项目使用jetty来为页面提供服务。这是我到目前为止的代码:
HTML部分:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
Java part1:
ContextHandler uploadContext = new ContextHandler();
uploadContext.setContextPath("/upload");
uploadContext.setBaseResource(getBaseResource());
uploadContext.setClassLoader(Thread.currentThread().getContextClassLoader());
uploadContext.setHandler(new UploadHandler());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] {uploadContext, configContext, sendGcodeContext, adjustManualLocationContext, getSystemStateContext, resourceHandler, new DefaultHandler()});
Java第2部分:
public class UploadHandler extends AbstractHandler{
@Override
public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String filename = getFilename(filePart);
System.out.println(filename);
baseRequest.setHandled(true);
}
}
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
如您所见,文件处理本身尚未出现;到目前为止只有文件名,因为这已经不起作用。
将显示以下消息:
HTTP 500错误,错误:Content-Type!= multipart / form-data
有人可以帮忙吗?我真的很沮丧,它仍然无效。
亲切的问候, 丹尼尔