Java教程

JavaWeb-文件下载

本文主要是介绍JavaWeb-文件下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

使用Tomact,servlet,HTML等,实现网页图片,视频的下载

servlet类:

package Dawnload;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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;

@WebServlet("/downloadservlet")
public class downloadservlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取请求参数,文件名称
        String filename = request.getParameter("filename");

        //找到文件服务器路径
        javax.servlet.ServletContext servletContext1 = this.getServletContext();
        String realPath = servletContext1.getRealPath("/img/" + filename);
        //使用字节流关联
        FileInputStream fileInputStream = new FileInputStream(realPath);

        //设置响应头类型
        String mimeType = servletContext1.getMimeType(filename);
        response.setHeader("content-type",mimeType);

        //设置中文乱码问题
        //获取user-agent请求头
        String  agent  =  request.getHeader("user-agent");
        //使用 工具类方法 编码文件名即可
        filename = coding.getfilename(agent,filename);

        //设置响应头打开方式
        response.setHeader("content-disposition","attachment;filename"+filename);


        //将输入流的数据写出到输出流中
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024 * 8];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }

        fileInputStream.close();  //关闭字节输入流
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

工具类:

          设置浏览器默认编码方式,解决文件名的中文乱码问题

package Dawnload;

import com.mchange.util.Base64Encoder;
import com.mchange.util.Base64FormatException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class coding {

    public static String getfilename(String agent ,  String filename)  {

        try {
            filename = URLEncoder.encode(filename,"utf-8");
            filename = filename.replace("+","");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
           
        return filename;
    }
}

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>下载</title>
</head>
<body>

<a href="/Java_Servlet/downloadservlet?filename=夏日.jpg">图片1</a>
<a href="/Java_Servlet/downloadservlet?filename=夏日.avi">视频1</a>

</body>
</html>

效果图:

这篇关于JavaWeb-文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!