2016-05-04 14 views
0

PostgreSQLにファイルアップロードを実装したいと思います。 InputStreamをPostgreSQLに挿入

public static byte[] getBytesFromInputStream(InputStream is) throws IOException 
    { 
     try (ByteArrayOutputStream os = new ByteArrayOutputStream();) 
     { 
      byte[] buffer = new byte[0xFFFF]; 

      for (int len; (len = is.read(buffer)) != -1;) 
       os.write(buffer, 0, len); 

      os.flush(); 

      return os.toByteArray(); 
     } 
    } 

    public void upload() throws SQLException 
    { 
     if (file != null) 
     { 
      try 
      { 
       InputStream inputStream = file.getInputStream(); 

       byte[] bytesFromInputStream = getBytesFromInputStream(inputStream); 
       ByteArrayInputStream input = new ByteArrayInputStream(bytesFromInputStream); 


       long lastTimestamp = System.currentTimeMillis(); 
       int pushInterval = 1000; 
       long totalRead = 0; 
       long size = file.getSize(); 

       int bytesRead = 0; 
       final byte[] chunck = new byte[1024]; 
       while ((bytesRead = inputStream.read(chunck)) != -1) 
       { 
//     outputStream.write(chunck, 0, bytesRead); 
        totalRead += bytesRead; 

        if (System.currentTimeMillis() > lastTimestamp + pushInterval) 
        { 
         lastTimestamp = System.currentTimeMillis(); 
         uploadProgress.send(100.0 * totalRead/size); // Make sure this isn't sent more often than once per second. 
        } 
       } 

       Connection conn = ds.getConnection(); 
       // insert into database file 
       PreparedStatement ps = null; 
       boolean committed = false; 
       try 
       { 
        conn.setAutoCommit(false); 

        ps = conn.prepareStatement("INSERT INTO PROCEDURE_FILES (ID, PROCEDURE_ID, FILE_NAME, FILE) " 
         + " VALUES (?, ?, ?, ?)"); 
        ps.setInt(1, obj.number); 
        ps.setInt(2, obj.number); 
        ps.setString(3, file.getSubmittedFileName()); 
        ps.setBinaryStream(4, input, input.available()); 

        ps.executeUpdate(); 
        ps.close(); 

        conn.commit(); 
        committed = true; 
       } 
       catch (SQLException e) 
       { 
        e.printStackTrace(); 
       } 
       finally 
       {} 
      } 
      catch (IOException e) 
      {} 
     } 
    } 

が、私はこのエラーを取得する:私は、このソリューションを試してみました

org.postgresql.util.PSQLException: ERROR: column "file" is of type oid but expression is of type bytea 
Hint: You will need to rewrite or cast the expression. 

私はこの問題を解決するにはどうすればよいですか?

+0

このリンクを見ることができます - https://virgo47.wordpress.com/2008/06/13/jpa-postgresql-and-bytea-vs-oid-type/ – Gandhi

+0

JPAは使用しません。 –

答えて

1

永続化する前に、InputStreamをOidオブジェクトにキャストする必要があります。そのためには、単に新しいOIDがあなたがISから取得するバイト配列を渡して作成します。

Oid oid = new Oid(IOUtils.readFully(inputStream, -1, false)); 

は、あなたが準備された文でOIDを渡します。

データベース側の別の解決策は、テーブルの列をBLOB型に変更することです。

+0

おそらく、私は 'inputStream'をキャストする必要があるのでしょうか? –

+0

ええ、私は誤解を誤っています。 – Aurasphere

+0

1つの一般的な質問。 1 GBのRAMを搭載したサーバーに2 GBのファイルをアップロードするとどうなりますか? –

関連する問題