我想使用JSP从文件存储在Mysql中的路径下载我的文件,实际上我做到了,但是下载文件时,它只有一个文件大小= 0 KB ,这里是我的代码下载:
package rizki;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "downloadServlet2", urlPatterns = {"/downloadServlet2"})
public class downloadServlet2 extends HttpServlet {
static ResultSet result;
static Connection con;
static PreparedStatement stat;
static Statement st, st2;
private static String dataSourceName="odbcMySql";
private static String dbURL="jdbc:odbc:"+dataSourceName;
private static String dbUser="root";
private static String dbPass="085219236994";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String id=request.getParameter("file_id");
String filePath="";
String fileName="";
String completeFile="";
String sql="select FileName,lokasi from savedFile where id= ?";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(dbURL,dbUser,dbPass);
stat=con.prepareStatement(sql);
stat.setString(1, id);
result=stat.executeQuery();
if (result.next())
{
fileName = result.getString(1);
filePath=result.getString(2);
}
completeFile=filePath+File.separator+fileName;
File downloadFile = new File(completeFile);
int length = 0;
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(completeFile);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
DataInputStream in = new DataInputStream(new FileInputStream(downloadFile));
byte[] buffer = new byte[4096];
//int bytesRead = -1;
while ((in != null) && ((length = in.read(buffer)) != -1))
{
outStream.write(buffer,0,length);
}
in.close();
outStream.close();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
这是我的代码将文件的路径存储到数据库,将文件存储到C:\ Users \ KikiRizki \ Documents \ NetBeansProjects \ BLH \ build \ web \ folderFile < / p>
<%@page import="java.sql.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.*, java.io.*" %>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>
<%@ page import="java.io.File"%>
<%@ include file="koneksiDB.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
try
{
String files="";
String fileName="";
File savedFile=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// Check that we have a file upload request
if(!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//ServletContext servletContext = this.getServletConfig().getServletContext();
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException Ex)
{
Ex.getMessage();
}
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
if (name.equals("files"))
{
files=value;
}
}
else
{
try
{
fileName = item.getName();
savedFile = new File (config.getServletContext().getRealPath("/")+"\\folderFile\\"+fileName);
item.write(savedFile);
}
catch (Exception ex)
{
out.println("error "+ex.getMessage());
}
}
}
try
{
//CallableStatement cs = koneksi.prepareCall("{call insertVideo2 (?,?)}");
String st = "insert into savedFile(fileName,lokasi,uploader) values (?,?,?)";
PreparedStatement psmt=cn.prepareStatement(st);
psmt.setString(1,fileName);
psmt.setString(2,savedFile.getPath());
psmt.setString(3, "ADMIN BLH");
psmt.executeUpdate();
psmt.close();
cn.close();
out.println("upload success!");
out.println(" back to home");
//st.executeUpdate("insert into video values ('"+VideoName+"')");
///response.sendRedirect("AdminVideo.jsp");
}
catch (Exception ex)
{
out.println("Error "+ex.getMessage());
}
}
}
catch (Exception Ex)
{
out.println("error" +Ex.getMessage());
}
%>
</body>
<a href="index2.jsp">Home Page</a>
</html>
如果我错了,请帮助或纠正,我非常感谢你的帮助,非常感谢
答案 0 :(得分:0)
package rizki;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "downloadServlet2", urlPatterns = {"/downloadServlet2"})
public class downloadServlet2 extends HttpServlet {
static ResultSet result;
static Connection con;
static PreparedStatement stat;
static Statement st, st2;
private static String dataSourceName="odbcMySql";
private static String dbURL="jdbc:odbc:"+dataSourceName;
private static String dbUser="root";
private static String dbPass="085219236994";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String id=request.getParameter("file_id");
String filePath="";
String fileName="";
String completeFile="";
String sql="select FileName,lokasi from savedFile where id= ?";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(dbURL,dbUser,dbPass);
stat=con.prepareStatement(sql);
stat.setString(1, id);
result=stat.executeQuery();
if (result.next())
{
fileName = result.getString(1);
filePath=result.getString(2);
}
completeFile=filePath+File.separator+fileName;
File downloadFile = new File(completeFile);
if(downloadFile.exists()){
int length = 0;
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(completeFile);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
//OutputStream outStream = response.getOutputStream();
//DataInputStream in = new DataInputStream(new FileInputStream(downloadFile));
FileInputStream in = new FileInputStream(downloadFile);
byte[] buffer = new byte[4096];
//int bytesRead = -1;
int i;
while ((i=in.read()) != -1) {
out.write(i);
}
in.close();
out.close();
}else{
System.out.println("File does not exist at location "+downloadFile.getAbsolutePath());
}
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
答案 1 :(得分:0)
-
public static InputStream getTheDbFileInputStreamWhereId(String id) {
try {
String sql = "select songFile from songs where id= ?";
Connection con = getConnectionGp();
PreparedStatement stat = con.prepareStatement(sql);
stat.setString(1, id);
ResultSet result = stat.executeQuery();
if (result.next()) {
return result.getBinaryStream(1);
}
} catch (Exception e) {
System.out.println("prolbem in dao dwonload");
e.printStackTrace();
}
return null;
}
-
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
String fileName = Dao.getFileNameWhereId(id);
if (fileName == null) {
System.out.println("file name not found!");
return;
}
String resContentType = "APPLICATION/OCTET-STREAM";
response.setContentType(resContentType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
InputStream in = Dao.getTheDbFileInputStreamWhereId(id);
if (in == null) {
System.out.println("file not found according to id");
return;
}
for (int i = in.read(); i != -1; i = in.read()) {
out.write(i);
}
in.close();
out.close();
} catch (Exception e) {
System.out.println("problem occurs");
}
}
答案 2 :(得分:-1)
您忘了刷新outStream.flush();
代码应为
while ((in != null) && ((length = in.read(buffer)) != -1))
{
outStream.write(buffer,0,length);
}
in.close();
outStream.flush();
outStream.close();
OutputStream outStream = response.getOutputStream();
将其更改为ServletOutputStream outStream = response.getOutputStream();
答案 3 :(得分:-1)
您可以清空outStream.flush();
更改此ServletOutputStream outStream = response.getOutputStream();到OutputStream outStream = response.getOutputStream();