我正在尝试将图像文件上传到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不会像我期待的那样表现,但不知道如何处理这个问题。请有人帮助我。