weibo_柠檬橙子y_0
2016-11-14 21:13
我的老是显示文件不存在下载失败 是不是在写文件名称的时候出错了呢?
在下载:<a href="download?filname=1.jpg">图片</a> ${errorResult}
图片1.jpg在WebContent/images下
package com.java1234.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取文件下载路径
String path=getServletContext().getRealPath("/")+"images";//下载的文件都放在images文件目录下
String filename=request.getParameter("filname");//获取到从前台得到的文件名称
File file=new File(path+filename);//读取文件
if(file.exists()){
//设置相应类型application/octet-stream
response.setContentType("application/x-msdownload");
//设置头信息
response.setHeader("Content-Disposition","attachment=\""+filename+"\"");
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
byte b[]=new byte[1024];
int n;
while((n=inputStream.read(b))!=-1){
outputStream.write(b,0,n);
}
//关闭流,释放流
outputStream.close();
inputStream.close();
}else{
request.setAttribute("errorResult","文件不存在下载失败!");
//重定向转发到jsp
RequestDispatcher dispatcher=request.getRequestDispatcher("download.jsp");
dispatcher.forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
String path=getServletContext().getRealPath("/")+"images";
image后面少了一个 斜杠 /
Java中的文件上传下载
77391 学习 · 337 问题
相似问题