[英]Downloading BLOB file has no data
我正在嘗試從MySQL下載BLOB數據,但我所能獲得的只是一個1 KB大小的文件。 我有一個包含復選框的表,正在尋找已選中的復選框。 這些值是ID。 這是代碼:
public class FileDownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DBConnection DBC = new DBConnection();
Connection con = DBC.connection();
String[] checkBoxValues = request.getParameterValues("files");
for (int i = 0; i < checkBoxValues.length; i++) {
String fileDL = "select * from uploads where file_id='"+checkBoxValues[i]+"'";
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(fileDL);
while(rs.next()){
String fileName = rs.getString("file_name");
Blob blob = rs.getBlob("file");
InputStream input = blob.getBinaryStream();
int fileSize = (int) blob.length();
System.out.println(fileSize);
ServletContext context = getServletContext();
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setContentLength(fileSize);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
input.close();
output.close();
}
} catch (SQLException ex) {
Logger.getLogger(FileDownloadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
我不知道哪里出了問題。 提前致謝!
output.write(buffer, 0, bytesRead)
始終使用相同的偏移量。 您永遠不會真正在結果流中前進。 您必須按bytesRead
增加偏移量
編輯:解釋
您正在使用https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html#write%28byte[],%20int,%20int%29此方法將字節寫入buffer
到輸出流,從位置0開始。現在,在下一個迭代中,讀取接下來的4k字節,然后再次將其寫入輸出流。 但是您的偏移量沒有改變,因此您沒有追加新的緩沖區內容,而是覆蓋了先前寫入的字節,因為您說要從位置0重新寫入。 因此,您需要將偏移量增加之前寫入的字節數。
編輯:擾流板
所以這是劇透:
int bytesRead = -1;
int offset = 0;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, offset, bytesRead);
offset += bytesRead;
}
未經測試。
另外,為什么要寫4k塊? 為什么不只是
byte[] buffer = new byte[1];
while (input.read(buffer) > 0) {
output.write(buffer);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.