Access (.mdb) file corrupted during servlet write to the client

一笑奈何 提交于 2019-12-24 06:38:55

问题


This was originally a part 2 of a different thread, but another use suggested that I separate the part 2 into it's own topic, so here we go. Original thread is here (Original Thread)

I am using Jackcess to create a V2010 mdb file that I need to transfer to a client that will use Access 2013 to open it. Jackcess itself works - V2010 creates a file that Access 2013 can open when the file is FTP'd to the client by a third party software, such as FAR. However, when I try to upload this file to the client through the servlet (as is the goal of this project), Access on the client says "Unrecognized database format "...file name...". This is the code used for upload. Code itself works, file is transferred, has a non-zero size if it's saved - but Access cannot open it.

Note, for content type I also tried vnd.msassess and octed-stream, with same unsuccessful results. Also, I tried closing the db and creating the FileInputStream from the file name, and, as in the example, tried to create FileInputStream by calling mydb.getFile(). No difference.

response.setContentType("application/vnd.ms-access");
String fileName = "SomeFileName.mdb"; 
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
Database mydb = generateMDBFile();
FileInputStream fis = new FileInputStream(mydb.getFile());
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024];
try {
     int byteRead = 0;
     while ((byteRead = fis.read()) != -1) {
           os.write(buffer, 0, byteRead);
     }
     os.flush();
 } catch (Exception excp) {
     excp.printStackTrace();
 } finally {
     os.close();
     fis.close();
 }

Why does this code corrupt the mdb file? This happens every time, regardless of the size (I tried a tiny 2 column/1 row file, and a huge file with 40 columns and 80000 rows)

Thank you!


回答1:


You forgot to fill the buffer. Use

// ...
while ((byteRead = fis.read(buffer)) != -1) {
       os.write(buffer, 0, byteRead);
 }
// ...


来源:https://stackoverflow.com/questions/27196153/access-mdb-file-corrupted-during-servlet-write-to-the-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!