如何在客户端获取/读取 xml 文件?
我需要创建一个网页,用户在其中提交 XML 文件,我用它来动态更新页面。
我正在遵循教程,并将这段代码放在 javascript 文件中:
function uploadFile(){
var path = "processXML?action=process&id=" + escape(fileChooser.value);
req = initRequest();
req.open("GET", path, true);
req.onreadystatechange = callback;
req.send(null);
}
我还在 Java Servlet 中设置了 URLpattern /processXMl。虽然我正在学习新的东西,但这并不是我想要实现的目标。 open() 方法指定服务器上的一个文件。
如何从客户端读取/接收 XML 文件,以便可以在服务器上的 Java 类中处理它?
I need to create a webpage where the user submits an XML file, which I use to dynamically update the page.
I am following a tutorial and have this piece of code in a javascript file:
function uploadFile(){
var path = "processXML?action=process&id=" + escape(fileChooser.value);
req = initRequest();
req.open("GET", path, true);
req.onreadystatechange = callback;
req.send(null);
}
I also have the URLpattern /processXMl set in a Java Servlet. Although I am learning something new, it's not what I am trying to achieve. The open() method is specifying a file on the server.
How do I read/receive an XML file from the client so I can process it within my Java classes on the server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
单独发送所选文件的文件名(或某些性能较差的浏览器中的文件路径)作为请求参数根本不起作用。您将无法以任何方式检索服务器端的文件内容(除非网络浏览器和网络浏览器恰好在物理上运行在同一台机器上,但这在实际生产中当然不会发生)。您需要让客户端发送文件内容。文件名只是元数据信息。
在 HTML5/XHR2 之前,通过 ajax 发送文件内容是不可能的,HTML5/XHR2 相对较新,目前仍在广泛使用的所有浏览器均不支持。我建议改为通过隐藏 iframe 中的表单来模拟异步文件上传。有很多 JavaScript 插件可以实现此目的,例如 jQuery Form 和 jQuery Uploadify。
要获取 servlet 中的文件内容,通常需要使用 Apache Commons FileUpload ,或者如果您已经使用了 Servlet 3.0,新的
HttpServletRequest#getParts()
方法。另请参阅:
Sending alone the file name (or the file path in some poor browsers) of the selected file as a request parameter isn't going to work at all. You will not be able to retrieve the file contents in the server side in any way (unless both the webbrowser and webbrowser happen to run in physically the same machine, but this does of course not occur in real production). You need to let the client send the file contents instead. The file name is just metadata information.
Sending the file contents by ajax was not possible until HTML5/XHR2, which is relatively new and not is supported in all browsers which are currently still widely in use. I'd suggest to simulate the asynchronous file upload by a form in a hidden iframe instead. There are lot of JavaScript plugins out for this, such as jQuery Form and jQuery Uploadify.
To obtain the file contents in a servlet, you'd usually use Apache Commons FileUpload for this, or if you're already on Servlet 3.0, the new
HttpServletRequest#getParts()
method.See also: