简体   繁体   English

jsp问题request.getparameter

[英]jsp problem request.getparameter

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? 我究竟做错了什么?

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. 问题是您正在尝试通过Webbrowser发送的名称从Web服务器的本地磁盘文件系统获取文件内容。 This is utterly wrong. 这是完全错误的。 Only Internet Explorer manifests the bug that it sends the full path instead of only the name. 只有Internet Explorer会显示它发送完整路径而不是仅发送名称的错误。 The full path is however useless to you since the webserver does normally not have access to the client's local disk file system. 然而,完整路径对您来说无用,因为Web服务器通常无法访问客户端的本地磁盘文件系统。

You should instead get the real file content from the request body which is sent by the webbrowser. 您应该从Webbrowser发送的请求正文中获取真实的文件内容。 To achieve this, you need to ensure that your HTML form has the method="post" and enctype="multipart/form-data" attributes. 为此,您需要确保HTML表单具有method="post"enctype="multipart/form-data"属性。

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>

Then, in the doPost() method of the servlet which is listening on URL pattern of /upload , use HttpServletRequest#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. 然后,在正在侦听/upload URL模式的servlet的doPost()方法中,使用HttpServletRequest#getParts()或当你仍然在Servlet 2.5或更早版本时,使用Apache Commons FileUpload来处理多部分的部分/ form-data请求。 It'll contain the uploaded file among the usual request parameters. 它将包含通常的请求参数中的上传文件。

See also: 也可以看看:

您可以在此处向用户检查Apache Commons File Upload。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM