我正在尝试将图像文件上传到 django Image 字段。除图像外,所有字段都被填充。
我的模型如下:
class ImageModel(models.Model):
image_title = models.CharField(max_length=50, null=False, blank=False)
uploader = models.CharField(max_length=50, null=False, blank=False)
image = models.ImageField(upload_to='imgs/', null=True, blank=True)
这是用于插入数据的 Java 代码片段:
String query = "INSERT INTO testapp_ImageModel (image_title , uploader , image) VALUES(?, ?, ?)";
File file = new File("Image location goes here");
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte [] buffer = new byte[1024];
for(int readNum; (readNum = fis.read(buffer)) != -1; ){
bos.write(buffer, 0, readNum);
System.out.println("Read " + readNum + " bytes...");
}
byte [] image = bos.toByteArray();
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, "Some Title");
ps.setString(2, "Uploader Name goes here");
ps.setBytes(3, image);
ps.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}
我知道 django 中的 ImageField 不会像我预期的那样表现,但不知道如何处理这个问题。请有人帮助我。