package controller;
import domain.File;
import jdbc.FileJdbc;
import jdbc.ServerJdbc;
import org.junit.Test;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
/**
* Created by Solitude on 2017-6-13.
*/
@WebServlet("/download")
public class download extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int serverId = Integer.parseInt(req.getParameter("serverId"));
String rootPath = "C:\\Users\\dell\\IdeaProjects\\myweb\\web\\WEB-INF\\settingfiles\\";
System.out.println("download");
int settingFileId = ServerJdbc.getSettingFileId(serverId);
System.out.println(settingFileId);
File file = FileJdbc.getFileById(settingFileId);
String absolutePath = rootPath + file.getFileSaveName() + file.getFileSuffix();
String realFileName = file.getFileName() + file.getFileSuffix();
InputStream inputStream = new FileInputStream(absolutePath);
//设置相应类型application/octet-stream
System.out.println(absolutePath + " " + realFileName);
resp.setContentType("application/x-msdownload");
resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(realFileName, "UTF-8"));
OutputStream outputStream = resp.getOutputStream();
System.out.println(absolutePath);
int len =-1;
byte[] b = new byte[1024];
while ((len=inputStream.read(b)) != -1){
outputStream.write(b, 0, len);
}
inputStream.close();
outputStream.close();
}
}
jsp/servlet下载文件
最新推荐文章于 2022-11-03 13:45:41 发布