如何使用更改的文件名重定向文件下载?
在这个Servlet类中,我放置了一个名为getContentType的函数来获取文件类型的名称。重定向到文件下载时,必须设置mimeType。
public class FileServlet extends HttpServlet {
String getContentType(String fileName) {
String extension[] = { //文件扩展名
"txt",// 0-纯文本
"htm",// 1-超文本
"jpg",// 2- JPEG图像
"png",// 2-JPEG图像
"gif",// 3-gif图像
"pdf",// 4-adobe pdf
"doc",// 5-Microsoft Word
"docx",
}; //您可以添加更多
String mimeType[] = { // mime类型
"text/plain", // 0-纯文本
"text/html", // 1-超文本
"image/jpg", // 2-jpg
"image/jpg", // 3-jpg
"image/gif", // 4- gif
"application/pdf", //4 - Adobe pdf
"application/msword", //5 - Microsoft Word
"application/msword", //5 - Microsoft Word
}, // 您可以添加更多
contentType = "text/html"; // 默认类型
// //点+文件扩展名
int dotPosition = fileName.lastIndexOf('.');
// //获取文件扩展名
String fileExtension =
fileName.substring(dotPosition + 1);
// 匹配mime类型来扩展
for (int index = 0; index < mimeType.length; index++) {
if (fileExtension.equalsIgnoreCase( extension[index])) {
contentType = mimeType[index];
break;
}
}
return contentType;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filename = request.getParameter("filename");
String realname = request.getParameter("realname");
String path = "C:\\web\\ftp_file\\";
String fullPath = path + filename;
File file = new File(fullPath);
String contentType = getContentType(filename);
System.out.println(contentType);
response.setContentType(contentType);
response.setHeader("Content-Disposition", "attachment; filename=" + realname);
int length = (int) file.length();
if (length > Integer.MAX_VALUE) {
}
byte[] bytes = new byte[length];
FileInputStream fin = new FileInputStream(file);
fin.read(bytes);
ServletOutputStream os = response.getOutputStream();
os.write(bytes);
os.flush();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/ **
*返回servlet的简短描述。
* @返回包含servlet描述的字符串
* /
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}