gpt4 book ai didi

java - 将图像保存到远程服务器

转载 作者:行者123 更新时间:2023-11-30 02:42:56 27 4
gpt4 key购买 nike

我正在寻找将文件保存到 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();
}

关于java - 将图像保存到远程服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41121169/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com