2016-12-13 9 views
1

複数のイメージを保存して取得する必要があるJavaプログラムがあるので、ファイルをMySQLデータベースに保存する最良の方法を探していました。私は最初のBLOBを持つテーブルをセットアップし、私が見つけたこのコードを使用して考える:イメージをリモートサーバに保存する

File image = new File("C:/image.jpg"); 
PrepareStatement psmnt = connection.prepareStatement 
("insert into save_image(image) "+ "values(?)"); 

FileInputStream fis = new FileInputStream(image); 
psmnt.setBinaryStream(3, (InputStream)fis, (int)(image.length())); 
/* executeUpdate() method execute specified sql query. Here this query 
insert data and image */ 
int s = psmnt.executeUpdate(); 

はしかし、私が連載された画像のためのMySQLデータベースを使用すると、パフォーマンスのために推奨されていないことを読んでいました。私はそれがサーバー内のディレクトリへのポインタを保存する方が良いと言われました。ファイルをダウンロードしてリモートサーバーにアップロードするにはどうすればよいですか?代わりにMySQLデータベースを使用することをお勧めしますか?

+0

画像を保存し、MySQLデータベースにその画像のURLを保存するためにAWS S3を使用することをお勧め。 – Sivailango

+1

イメージをデータベースに保存せず、イメージをファイルシステムに保存し、イメージへのパスを保存します(後で取得するため)。 –

答えて

2

ソケットを使用してイメージをサーバーに転送できます。 これはクライアントとサーバー間の通信であり、送信者と受信者のプログラムが必要です。

クライアント(送信者)

public static void sendFileToServer() throws Exception { 
     Path path = Paths.get("path/to/file"); 
     byte[] data = Files.readAllBytes(path); 

     // port has to be the same on client and server side 
     int port = 1337; 

     //create a socket connection to the server 
     Socket socket = new Socket("ipAdressOfTheServer", port); 
     OutputStream out = socket.getOutputStream(); 

     // first write the length of the file so the receiver knows how much it has to read 
     out.write(ByteBuffer.allocate(4).putInt(data.length).array()); 
     //write the actual file data 
     out.write(data, 0, data.length); 
     socket.close(); 
    } 

サーバー(レシーバー)

public static void receiveFile() throws Exception { 
     //create a ServerSocket to listen for incoming connections 
     ServerSocket server = new ServerSocket(1337); 
     Socket senderSocket = server.accept(); 
     DataInputStream in = new DataInputStream(senderSocket.getInputStream()); 
     //first read the length of the file 
     int lengthOfFile = in.readInt(); 
     byte[] buffer = new byte[lengthOfFile]; 

     //then read the actual file bytes 
     in.readFully(buffer); 

     FileOutputStream fos = new FileOutputStream("pathname"); 
     fos.write(buffer); 
     fos.close(); 
    } 
関連する問題