JavaWeb服务器上传下载方法

1.简单上传 

JSP页面需要注意enctype="multipart/form-data"

后端的xml文件配置如下。在注册类的时候加上<multipart-config/>

后端代码如下:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String savaPath ="D://";//路径
            Part part = req.getPart("file");//前端定义上传文件input框名字
    		String header = part.getHeader("content-disposition");//头
    		part.write(savaPath+getFilename(header));
    		//getFilename(header)通过下面写好的方法将文件名取出来
    		//part.write();将文件输出
	}
	public String getFilename(String header){
		if(header!=null){
			String[] temp=header.split("=");
			String str=temp[temp.length-1];
			return str.replace("\"", "");
		}else{
			return null;
		}
	}

2.下载

前端采用的A标签,需要下载的文件名用?传参。

<a href="downLoadServlet?filename=apache-tomcat-8.5.24-windows-x86.zip">apache-tomcat-8.5.24-windows-x86.zip</a>

后台代码

                String filename=req.getParameter("filename");//获取前端传过来的文件名
		//通过ServletContext对象获取文件所在的绝对路径
		String realFilename = req.getServletContext().getRealPath("/WEB-INF/download/"+filename);
		//通过ServletContext对象getMimeType(filename)获取文件MimeType
		String mimeType = req.getServletContext().getMimeType(realFilename);
		//通过Response的setContentType()设置文件输出类型
		resp.setContentType(mimeType);
		//设置响应头,告诉浏览器要下载的文件是否在浏览器中显示,inline表示内嵌显示,attachment表示弹出下载框
		resp.setHeader("Content-Disposition", "inline;filename="+filename);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realFilename));//创建字节缓冲流
		OutputStream out = resp.getOutputStream();//获取输出流
		int len=0;
		while((len=bis.read())!=-1){
			out.write(len);//输出到客户端
		}
		bis.close();
		out.close();

3.将WEB-INF/down目录下的所有文件遍历输出到页面,提供下载链接

前端代码

<c:forEach items="${downMap}" var="fileMap">//此处用的jstl。
   <c:url value="down" var="downurl">
    <c:param name="filename" value="${fileMap.key}"></c:param>
   </c:url>
   ${fileMap.key}<a href=${downurl}>下载</a>//${downurl}等于"down?filename=${fileMap.key}"
</c:forEach>

后台代码:

负责遍历并把内容输出到页面:

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String realPath = req.getServletContext().getRealPath("/WEB-INF/down/");
		Map<String,String> map = new HashMap<String,String>();
		readDown(new File(realPath),map);//将文件名和地址放在map集合中
		req.getSession().getServletContext().setAttribute("downMap", map);//放在session域中,方便前端获取。
	}
	public void readDown(File file,Map<String,String> map) {//递归遍历获得down目录下面的所有文件
		if(!file.isFile()) {
			File[] listFiles = file.listFiles();
			for (File file2 : listFiles) {
				readDown(file2,map);
			}
		}else {
			System.out.println(file.getAbsolutePath());
			map.put(file.getName(), file.getAbsolutePath());
		}

负责下载:

                String filename=req.getParameter("filename");//获取前端传过来的文件名
		//通过ServletContext对象获取文件所在的绝对路径
		String realFilename = req.getServletContext().getRealPath("/WEB-INF/download/"+filename);
		//通过ServletContext对象getMimeType(filename)获取文件MimeType
		String mimeType = req.getServletContext().getMimeType(realFilename);
		//通过Response的setContentType()设置文件输出类型
		resp.setContentType(mimeType);
		//设置响应头,告诉浏览器要下载的文件是否在浏览器中显示,inline表示内嵌显示,attachment表示弹出下载框
		resp.setHeader("Content-Disposition", "inline;filename="+filename);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realFilename));//创建字节缓冲流
		OutputStream out = resp.getOutputStream();//获取输出流
		int len=0;
		while((len=bis.read())!=-1){
			out.write(len);//输出到客户端
		}
		bis.close();
		out.close();

猜你喜欢

转载自blog.csdn.net/Jack_HuzZ/article/details/85300401