jsp问题request.getparameter
我用来
<input type="file" name="file" value="">
浏览要上传的图像文件。但是当我在操作页面使用时
String imageUrl = request.getParameter("file");
out.println("logofile" + imageUrl);
,它只显示图像名称而不是完整的绝对路径。当我尝试使用
File file = new File(imageUrl);
它时会抛出以下异常
java.io.FileNotFoundException: apple-logo.jpg (The system cannot find the file specified)
我做错了什么?
I am using
<input type="file" name="file" value="">
to browse the image file for upload. But when I use
String imageUrl = request.getParameter("file");
out.println("logofile" + imageUrl);
at the action page, it only shows the image name not the full absolute path. When I try to use
File file = new File(imageUrl);
it throws the following exception
java.io.FileNotFoundException: apple-logo.jpg (The system cannot find the file specified)
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您试图通过网络浏览器发送的名称从网络服务器的本地磁盘文件系统获取文件内容。这是完全错误的。只有 Internet Explorer 存在发送完整路径而不是仅发送名称的错误。然而,完整路径对您来说毫无用处,因为网络服务器通常无法访问客户端的本地磁盘文件系统。
您应该从网络浏览器发送的请求正文中获取真实的文件内容。为此,您需要确保 HTML 表单具有
method="post"
和enctype="multipart/form-data"
属性。然后,在监听
/upload
URL 模式的 servlet 的doPost()
方法中,使用HttpServletRequest#getParts()
或当您如果仍然使用 Servlet 2.5 或更早版本,请使用 Apache Commons FileUpload 处理 multipart/form 的各个部分-数据请求。它将在常用请求参数中包含上传的文件。另请参阅:
The problem is that you're trying to get the file content from the webserver's local disk file system by the name sent by the webbrowser. This is utterly wrong. Only Internet Explorer manifests the bug that it sends the full path instead of only the name. The full path is however useless to you since the webserver does normally not have access to the client's local disk file system.
You should instead get the real file content from the request body which is sent by the webbrowser. To achieve this, you need to ensure that your HTML form has the
method="post"
andenctype="multipart/form-data"
attributes.Then, in the
doPost()
method of the servlet which is listening on URL pattern of/upload
, useHttpServletRequest#getParts()
or when you're still on Servlet 2.5 or older, use Apache Commons FileUpload to process the parts of the multipart/form-data request. It'll contain the uploaded file among the usual request parameters.See also:
您可以在此处查看以使用 Apache Commons 文件上传。
You can user check here to user Apache Commons File Upload.