简体   繁体   English

Java EE-将图像上传到数据库?

[英]Java EE - Upload image to database?

I'm making a fairly basic site for my mother, and seeing as I did some stuff in Java EE and with EJB during college last semester, I'm going to stick to this. 我正在为我的母亲创建一个相当基本的站点,并且看到上学期在Java EE和EJB中做了一些工作时,我会坚持下去。

The only issue I am having is uploading images - I can't seem to find any examples. 我唯一的问题是上传图片-我似乎找不到任何示例。

I'm using entity classes and parameterised queries. 我正在使用实体类和参数化查询。 This is the code for writing to the database, which is working fine, I'm just setting the blob image value to null for the moment. 这是用于写入数据库的代码,效果很好,我现在只是将blob图像值设置为null。

@Override
    public void addClothes(String designer, String cname, String ctype, String desc) {
        Clothes c = new Clothes();
        em.persist(c);
        c.setDesigner(designer);
        c.setCname(cname);
        c.setCtype(ctype);
        c.setDescript(desc);
        c.setImage(null);
    }

I have a servlet that takes a file, I'm just not sure how the file, when passed, should be sorted and what I should write to the database (from what I'm seeing, it's byte[]) 我有一个接收文件的servlet,但我不确定该文件在传递时应如何排序以及应写入数据库的内容(从我看到的内容来看,它是byte [])。

A hand in the right direction would be appreciated! 朝正确方向伸出的手将不胜感激!

Once you have the file on the server, either in memory or in a local or temp file (that depends on the framework or libraries that you're using), you will have a reference of a wrapper type. 将文件放在服务器上的内存中或本地或临时文件中(取决于所使用的框架或库)之后,您将拥有包装类型的引用。

If you are using Apache Commons File Upload , you have a FileItem reference. 如果您正在使用Apache Commons File Upload ,则有FileItem参考。 For request all contents of the file as byte array: 对于请求文件的所有内容为字节数组:

byte[] contents = fileItem.get();

If you are using Tomahawk of Trinidad , you have a org.apache.myfaces.trinidad.model.UploadedFile reference. 如果使用的是特立尼达的战斧 ,则有org.apache.myfaces.trinidad.model.UploadedFile参考。 For request all contents of the file as byte array, you can use class IOUtils of the Apache Commons IO : 为了将文件的所有内容请求为字节数组,可以使用Apache Commons IO的 IOUtils类:

byte[] contents = IOUtils.toByteArray(uploadedFile.getInputStream());

Of if you have a reference of org.apache.myfaces.custom.fileupload.UploadedFile , is more simple: 如果您有org.apache.myfaces.custom.fileupload.UploadedFile的引用,则更为简单:

byte[] contents = uploadedFile.getBytes();

UPDATE 更新

If you are using Java EE 6, you can use new features of Server 3.0 specification for upload files without extra libraries. 如果使用的是Java EE 6,则可以使用Server 3.0规范的新功能来上传文件,而无需额外的库。 See the excellent tutorial of BalusC in The BalusC Code: Uploading files in Servlet 3.0 请参阅BalusC代码中出色的BalusC教程:在Servlet 3.0中上传文件

To work with hibernate http://www.mkyong.com/hibernate/hibernate-save-image-into-database/ 使用休眠http://www.mkyong.com/hibernate/hibernate-save-image-into-database/

To work with JDBC: 要使用JDBC:

To Write image into database BLOB using Jdbc , You need to Convert the File into Inputstream. 要使用Jdbc将图像写入数据库BLOB,您需要将文件转换为Inputstream。 statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length())); statement.setBinaryStream(2,(InputStream)inputStream,(int)(image.length())); PreparedStatement statement offer method setBinaryStream() which is used to write binary stream into database BLOB column. PreparedStatement语句提供方法setBinaryStream(),该方法用于将二进制流写入数据库BLOB列。

Here is a code snippet to help you: 以下代码段可为您提供帮助:

File image = new File("C:/test.jpg");
inputStream = new FileInputStream(image);

Prepared statement = //define as per your table
// set the file binary stream 
statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length()));

statement.executeUpdate();

In your Clothes class, you can add: 在您的衣服课中,您可以添加:

@Lob
private byte[] image;

// Getter/Setter methods

Got it working ! 得到它的工作! Somewhat, with this code: 通过以下代码:

public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        out = response.getWriter();
        final String path = "clothesImages" + File.separator + request.getParameter("designer") + File.separator + request.getParameter("ctype") + File.separator + request.getParameter("cname");
        out.println(path);
        String currentDir = new File(".").getAbsolutePath();
        out.println(currentDir);
        final Part filePart = request.getPart("image");
        final String filename = "image.jpg";
        File file = new File(path);
        if (!file.exists()){
            out.println("Dir Doesn't Exist");
            file.mkdirs();
        }
        OutputStream outstream = null;
        InputStream filestream = null;

        try{
         outstream = new FileOutputStream(new File(path + File.separator + filename));
         filestream = filePart.getInputStream();
         int read = 0;
         final byte[] bytes = new byte[1024];
         while(( read = filestream.read(bytes)) != -1){
             outstream.write(bytes, 0, read);
         }
         out.println("New file " + filename + " created at " + path);
        }catch (FileNotFoundException fne) {
        out.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        out.println("<br/> ERROR: " + fne.getMessage());
        }finally {
        if (out != null) {
            out.close();
        }
        if (filestream != null) {
            filestream.close();
        }
        if (outstream != null) {
            outstream.close();
        }
    }

    }

The only issue I have is setting the file path. 我唯一的问题是设置文件路径。 The path is 路径是

C:\\Users\\Chris\\AppData\\Roaming\\NetBeans\\7.2.1\\config\\GF3\\domain1\\ C:\\ Users \\ Chris \\ AppData \\ Roaming \\ NetBeans \\ 7.2.1 \\ config \\ GF3 \\ domain1 \\

But I want it to save in 但我要保存

Project-war/web/images Project-war / web / images

Any ideas? 有任何想法吗?

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

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