java上传图片并存到mysql数据库代码
时间: 2023-11-13 14:12:17 浏览: 109
基于java+springboot的考勤系统毕业设计源码+数据库(高分优秀项目)
以下是将图片上传并存储到MySQL数据库的Java代码示例:
```
import java.io.*;
import java.sql.*;
public class ImageUpload {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOURDBNAME";
String username = "YOURUSERNAME";
String password = "YOURPASSWORD";
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
File image = new File("path/to/image.jpg");
FileInputStream fis = new FileInputStream(image);
pstmt = conn.prepareStatement("INSERT INTO images (filename, content) VALUES (?,?)");
pstmt.setString(1, image.getName());
pstmt.setBinaryStream(2, fis, (int) image.length());
pstmt.executeUpdate();
System.out.println("Image has been uploaded to the database.");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
}
```
请注意,将占用大量内存的图像文件存储在数据库中可能不是最佳选择,并且会降低数据库性能。在实际应用中,通常更好的解决方案是将图像文件保存到服务器上,并在数据库中存储图像的文件路径。
阅读全文