将图像保存到远程服务器

时间:2016-12-13 12:29:17

标签: java

我正在查找将文件保存到MySQL数据库的最佳方法,因为我有一个需要保存和检索多个图像的Java程序。我首先想到用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数据库吗?

1 个答案:

答案 0 :(得分: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();
    }