通过Spring MVC将二进制文件上传到MySQL的正确方法

我正在尝试将文件上传到MySQL,但是我无法正确地执行此操作。 我正在使用云平台将Java Spring应用程序作为网站运行。

控制器:

byte[] bytes = file.getBytes(); // file is MultipartFile DFile newFile = new DFile(); // my object newFile.setName(name); // name column newFile.setType(type); // Blob blob = new SerialBlob(bytes); // set the blob from binary newFile.setData(blob); fileService.insertFile(newFile); // calls to insert into MySQL 

道:两种不同的方式

  length = (int)blob.length(); byte[] b = blob.getBytes(1, length); InputStream is=new ByteArrayInputStream(b); LobHandler lobHandler = new DefaultLobHandler(); // method 1 jdbcTemplate.update( sql, new Object[] { dFile.getName(), dFile.getType(), blob,}, new int[] {Types.VARCHAR, Types.VARCHAR, Types.BLOB}); // method 2 Connection con; PreparedStatement ps; ps = con.prepareStatement(sql); ps.setString(1, dFile.getName()); ps.setString(2, dFile.getType()); ps.setBinaryStream(3, is, length); int count = ps.executeUpdate(); 

来自文件的原始数据

 0000-0010: ff d8 ff e0-00 10 4a 46-49 46 00 01-01 01 00 90 ......JF IF...... 0000-0020: 00 90 00 00-ff db 00 43-00 02 01 01-02 01 01 02 .......C ........ 0000-0030: 02 02 02 02-02 02 02 03-05 03 03 03-03 03 06 04 ........ ........ 0000-0040: 04 03 05 07-06 07 07 07-06 07 07 08-09 0b 09 08 ........ ........ 

从MySQL提供的数据

 0000-0010: ef bf bd ef-bf bd ef bf-bd ef bf bd-00 10 4a 46 ........ ......JF 0000-0020: 49 46 00 01-01 01 00 ef-bf bd 00 ef-bf bd 00 00 IF...... ........ 0000-0030: ef bf bd ef-bf bd 00 43-00 02 01 01-02 01 01 02 .......C ........ 0000-0040: 02 02 02 02-02 02 02 03-05 03 03 03-03 03 06 04 ........ ........ 

我是如何创建表文件的:

  String create ="CREATE TABLE File ( "name varchar(255) character set utf8 not null, type varchar(64) character set utf8 not null, data mediumblob, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, primary key (name) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

事实:

  1. 该网站有一个旧的和新的phpAdmin页面来执行sql操作。 旧的Web界面无法上载正确的图像文件。 如果使用我的代码上传,错误的文件似乎是相同的。 新的PhpAdmin在上传时有一个Binary选项,它可以工作。
  2. 我在所有Web服务中使用UTF-8,包括web.xml中的CharsetFilter和SQL字符集。
  3. 我使用类似的代码但在Controller中反转以提供文件,如果我使用新的web phpAdmin加载,它可以显示正确的图像文件。

题:

什么地方出了错? 我猜它可能是字符编码。 如何解决问题?

尝试使用以下样式

 insert into File (name, type, data) values ("good.bin", "binary", 0x01020304) 

你试过这个:

 jdbcTemplate.execute("INSERT INTO File (name, type, data) VALUES (?, ?, ?)", new AbstractLobCreatingPreparedStatementCallback(lobHandler){ @Override protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException, DataAccessException { ps.setString(1, dFile.getName()); ps.setString(2, dFile.getType()); Blob blob = dFile.getData(); int length = (int)blob.length(); byte[] b = dFile.getData(); //blob.getBytes(1, length); int length = b.length; InputStream is=new ByteArrayInputStream(b); ps.setBinaryStream(3, is, length); } });