fastfds上传多张图片到数据库
时间: 2023-09-13 19:09:43 浏览: 55
首先,你需要创建一个存储图片的表,可以包含以下字段:
- `id`: 图片的唯一标识符
- `name`: 图片的名称
- `type`: 图片的类型
- `size`: 图片的大小
- `data`: 图片的二进制数据
接下来,你可以使用 `FastDFS` 提供的客户端 API 上传图片到 `FastDFS` 服务器,并获取图片的路径,例如:
```java
import org.csource.fastdfs.*;
public class FastDFSClient {
private static TrackerClient trackerClient;
private static StorageClient storageClient;
static {
try {
ClientGlobal.init("fdfs_client.conf");
TrackerClient trackerClient = new TrackerClient();
StorageClient storageClient = new StorageClient(trackerClient.getConnection(), null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String upload(byte[] data, String fileName) {
try {
String[] results = storageClient.upload_file(data, "jpg", null);
String path = results[0] + "/" + results[1];
return path;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
最后,你可以将图片的路径以及其他信息保存到数据库中,例如:
```java
import java.sql.*;
public class ImageDao {
private static final String URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
private static final String USER = "root";
private static final String PASSWORD = "123456";
private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
static {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void save(String name, String type, long size, byte[] data) {
String path = FastDFSClient.upload(data, name);
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
String sql = "INSERT INTO images(name, type, size, path) VALUES (?, ?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, name);
stmt.setString(2, type);
stmt.setLong(3, size);
stmt.setString(4, path);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
这样,你就可以通过调用 `ImageDao.save()` 方法来上传多张图片并保存到数据库了。