【发布时间】:2023-03-21 13:08:01
【问题描述】:
我正在尝试从 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);
}
}
}
}
我不知道我哪里出错了。提前致谢!
【问题讨论】:
标签: java mysql jsp servlets blob