java_文件上传/下载

1、文件上传

  • JSP
1. 设置input的type设置为file
2. form表单的method设置为post get请求回将文件名字传给后台而不是文件本身
3.form的表单的enctype设置multipart/form-data,以二进制形式传递数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


   

  • Servlet
@WebServlet("/upload")
public class uploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //通过输入流获取客户端传来的数据 读到内存
        InputStream inputStream =  req.getInputStream();
        Reader reader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(reader);
        //通过输出流将数据流输出到本地硬盘
        //获取文件夹的绝对路径
        String path = req.getServletContext().getRealPath("/file/copy.txt");
        OutputStream outputStream = new FileOutputStream(path);
        Writer writer = new OutputStreamWriter(outputStream);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        String str = "";
        while ((str = bufferedReader.readLine())!=null){
            bufferedWriter.write(str);
        }
        bufferedReader.close();
        bufferedWriter.close();
        outputStream.close();;
        writer.close();
        reader.close();
        inputStream.close();
    }
}
输入文件copy.txt
  • 组件: fileupload 阿帕奇
  导入jar包
1. common-io.jar
2. commons.fileupload.jar

1.fileupload:组件可以将所有的请求信息都解析成FileItem对象 可以通过对fileItem对象的操作完成上传 面向对象操作
2.读取文本文件使用字节流 会把文本中的段落 空格都可以读取 同时也可以读取图片,而字符流只能读取文字 不能识别段落 空格和图片

@WebServlet("/upload")
public class uploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload =  new ServletFileUpload(fileItemFactory);
        try {
            List list = servletFileUpload.parseRequest(req);
            for (FileItem fileItem:list){
                System.out.println(fileItem.getName());//test.txt
                System.out.println(fileItem.getFieldName());//img 对应jsp标签的name  
//如果是文本 if (fileItem.isFormField()){ String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8"); System.out.println(value); }else { //文件 InputStream inputStream = fileItem.getInputStream(); String path = req.getServletContext().getRealPath("/file/"+fileItem.getName()); OutputStream outputStream = new FileOutputStream(path); int temp = 0; while ((temp = inputStream.read())!=-1){ outputStream.write(temp); } outputStream.close(); inputStream.close(); System.out.println("输出成功"); } } } catch (FileUploadException e) { e.printStackTrace(); } } }
image.png

2、文件下载

@WebServlet("/downloadServlet")
public class downloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应的方式 下载
        resp.setContentType("application/x-msdownload");
        String fileName =  "1.png";
        //设置下载后的文件名
        resp.setHeader("Content-Disposition","attachment:filename="+fileName);
        //获取输出流
        OutputStream outputStream = resp.getOutputStream();
        String path = req.getServletContext().getRealPath("file/download.png");
        InputStream inputStream = new FileInputStream(path);
        int temp = 0;
        while ((temp = inputStream.read()) != -1){
            outputStream.write(temp);
        }
        inputStream.close();
        outputStream.close();
    }
}

你可能感兴趣的:(java_文件上传/下载)