gpt4 book ai didi

java - 下载的 BLOB 文件没有数据

转载 作者:行者123 更新时间:2023-11-29 23:21:58 26 4
gpt4 key购买 nike

我正在尝试从 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此方法将缓冲区中的字节写入输出流,从位置 0 开始。现在,在下一次迭代中,您读取接下来的 4k 字节并再次将其写入输出流。但是你的偏移量没有改变,所以你不追加新的缓冲区内容,而是覆盖以前写入的字节,因为你说再次从位置 0 写入。因此,您需要将偏移量提前与之前写入的字节数相同。

编辑:剧透

以下是剧透:

int bytesRead = -1;
int offset = 0;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, offset, bytesRead);
offset += bytesRead;
}

未经测试。

另外,为什么要以4k block 的形式写入呢?为什么不只是

byte[] buffer = new byte[1];
while (input.read(buffer) > 0) {
output.write(buffer);
}

关于java - 下载的 BLOB 文件没有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27233116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com