码迷,mamicode.com
首页 > 编程语言 > 详细

java实现从服务端下载文件

时间:2018-12-24 02:34:22      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:app   row   简单   string   inpu   except   while   throws   tst   

这边用一个简单的servlet实现java从服务端下载文件的操作

 

 写一个servlet:

  <servlet>
    <servlet-name>DownloadServlet</servlet-name>
    <servlet-class>DownloadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DownloadServlet</servlet-name>
    <url-pattern>/download</url-pattern>
  </servlet-mapping>

 

java代码:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class DownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = "D:\\360MoveData\\Users\\123\\Desktop\\WebComponents.exe";
        String fileName = "WebComponents.exe";
        String fileType = "application/octet-stream";

        //设置文件的类型
        response.setContentType(fileType);
        // 确保弹出下载对话框
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        FileInputStream inputStream = new FileInputStream(filePath);
        //输出流
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[4096];
        int length;
        while ((length = inputStream.read(bytes)) > 0){
            outputStream.write(bytes, 0, length);
        }
        inputStream.close();
        outputStream.flush();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response);
    }
}

 

java实现从服务端下载文件

标签:app   row   简单   string   inpu   except   while   throws   tst   

原文地址:https://www.cnblogs.com/chenmz1995/p/10166087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!