我一直在寻找将文件保存到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数据库?
您可以使用套接字将映像传输到服务器。这将是客户端/服务器通信,因此您需要发送者和接收者程序。
客户(发件人)
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句