使用htm输入类型=文件存储图像
您好,我正在构建一个网络应用程序(在线商店),管理员可以在其中上传新产品。 输入类型之一是文件(产品图像) 我希望将产品的图像存储在一个文件夹中,并且每个产品在数据库表中都会有一个关联的图像。
我的问题是,输入类型=文件如何工作?我仍然不明白当我提交表单时,servlet 如何将图像粘贴到网页文件夹中,以及如何获取值(图像的名称)并将其存储在数据库表中?
对于其他输入,我使用“值”来获取信息。
谢谢!
Hello I'm building a web application (online store) where an admin can upload a new product.
One of the input type is a file (image of the product)
I want the images of the products to be stored in a folder, and each product will have an image associated in the database table.
My question is, how does input type=file work? I still don't understand how when I submit the form a servlet will paste the image in the webpage folder, and how is the value (name of the image) going to be obtained to be stored in the database table?
For the other inputs i use "value" to get the info.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在java中,很难处理文件上传。但有很多图书馆都这样做。 是一个关于如何在 java 中执行此操作的示例:
最流行的一个是 apache commons file uploads下面 还有更多您应该尝试的选项。
In java, its hard to do handle file uploads. But there are many libraries that do it. The most popular one is apache commons file uploads Here is an example on how to do that in java:
There are many more options that you should play around with.
这将在
另请参阅:
您不应该只对文件名感兴趣。您还应该对文件内容感兴趣。无论您选择如何从请求正文中解析上传的文件,最终都应该得到
InputStream
或byte[]
风格的文件内容。您可以使用 FileOutputStream 将其写入本地磁盘文件系统,并以通常的 JDBC 方式将唯一的文件名存储在数据库中。另请参阅:
This is to be used in a
<form>
withmultipart/form-data
encoding. Once a file is selected and the form is submitted, then the file contents becomes part of the HTTP request body. In the servlet, it's available as "raw" data byrequest.getInputStream()
. In servletcontainers supporting only servlet 2.5 or older, there was no API-provided facility to parse the data. Apache Commons FileUpload is the de facto standard. Since servlet 3.0 you can use the API-providedrequest.getParts()
for this -which is under the covers using a licensed copy of Commons FileUpload.See also:
You should not only be interested in the file name. You should also be interested in the file contents. Whatever way you choose to parse the uploaded file out of the request body, you should end up with the file contents in flavor of an
InputStream
or abyte[]
. You can write it to local disk file system usingFileOutputStream
and store the unique filename in the DB the usual JDBC way.See also:
将文件上传到 Web 服务器时,通常会包含以下信息(或类似信息):
filename
包含文件名或完整路径,具体取决于浏览器。如果您使用像 Fiddler 这样的程序,您可以准确地看到上传文件时发生的情况。
When a file is uploaded to a web server, the following information is usually included (or similar):
The
filename
contains either the name of the file or the full path depending on the browser.If you use a program like Fiddler, you can see exactly what's going on when you upload a file.