如何上传图像并将其保存在数据库中? [英] How to upload an image and save it in database?
问题描述
我必须使用JavaScript创建一个表单,用户将上传一个JPG文件并提交其他信息,如姓名,电子邮件等。当用户单击提交时,表单中的所有信息将被加载到一个值目的。对于图像文件,我将它设置为 byte []
。
I have to create a form using JavaScript and an user will upload a JPG file and submit along with other info such as name, email, etc. When the user clicks submit all the information from the form will be loaded to a value object. For the image file I've set it to be byte[]
.
So assuming:
public String name;
public String email;
public byte[] logo;
我设置了一个servlet来处理提交,但我不知道如何开始。上传如何工作?当用户提交时,如何获取图像的信息?以下是屏幕截图: http://imageshack.us/f/32/77675354.png/我需要转换该图像并将其保存到 byte []
,然后转换为blob,以便我可以将其插入表。
I've set up a servlet as well to handle the submission but I'm not sure how to get started. How does the upload work? When user submits, how do I get the information for the image? Here's a screenshot: http://imageshack.us/f/32/77675354.png/ I need to convert that image and save it to a byte[]
then convert to blob so I can insert it to a table.
推荐答案
对于文件上传部分,您需要设置 enctype =multipart / form-data
HTML表单,以便webbrowser将发送文件内容,并且您想在servlet的 doPost()中使用
request.getPart()
code>方法将文件作为 InputStream
获取。有关具体代码示例,另请参见如何将文件上传到服务器使用JSP / Servlet?
For the file upload part, you need to set enctype="multipart/form-data"
on the HTML form so that the webbrowser will send the file content and you'd like to use request.getPart()
in servlet's doPost()
method to get the file as an InputStream
. For a concrete code example, see also How to upload files to server using JSP/Servlet?
然后,要在DB中保存 InputStream
a href =http://download.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setBinaryStream%28int,%20java.io.InputStream%29 =nofollow> PreparedStatement#setBinaryStream()
BLOB
/ varbinary
/ bytea
列或任何列表示您最喜欢的数据库引擎中的二进制数据。
Then, to save this InputStream
in the DB, just use PreparedStatement#setBinaryStream()
on a BLOB
/varbinary
/bytea
column or whatever column represents "binary data" in your favorite DB engine.
preparedStatement = connection.prepareStatement("INSERT INTO user (name, email, logo) VALUES (?, ?, ?)");
preparedStatement.setString(1, name);
preparedStatement.setString(2, email);
preparedStatement.setBinaryStream(3, logo);
// ...
您不一定需要转换此 InputStream
到 byte []
,它也不会有内存高效。假设100个用户同时上传10MB的图像,那么1GB的服务器内存将在那时分配。
You don't necessarily need to convert this InputStream
to byte[]
, it would not have been memory efficient either. Imagine that 100 user simultaneously upload images of 10MB, then 1GB of server memory would have been allocated at that point.
这篇关于如何上传图像并将其保存在数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!