总是显示文件不存在下载失败 不知道问题出在哪里

来源:2-6 实现文件下载

weibo_柠檬橙子y_0

2016-11-14 21:13

我的老是显示文件不存在下载失败 是不是在写文件名称的时候出错了呢?

在下载:<a href="download?filname=1.jpg">图片</a> &nbsp;&nbsp; ${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);

}


}





写回答 关注

1回答

  • 黑马非马1013
    2016-11-22 21:41:43

    String path=getServletContext().getRealPath("/")+"images";

    image后面少了一个 斜杠 /

Java中的文件上传下载

由简入深,轻松实现文件上传下载功能及相关框架的使用

77391 学习 · 337 问题

查看课程

相似问题