10、JavaWeb-upload文件上传

  • Post author:
  • Post category:java


参考链接:


FileUpload – Home



Commons IO – Commons IO Overview

一、不推荐的上传文件的逻辑(代码繁琐逻辑简单)

index15_upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>upload</title>
</head>
<body>
<%--<form action="servlet14_Upload" method="get">--%>
<%--<form action="servlet14_Upload" method="post">--%>
<form action="servlet14_Upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="提交上传的文件">
</form>
<p>可以提交文件、图片等文件</p>
<p>如果提交的txt文件后台直接读取txt文件中的字符串</p>
</body>
</html>

Servlet14_Upload.java

package com.test.app;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author:
 * @date:2022/1/18
 * @description:
 */
@WebServlet("/servlet14_Upload")
public class Servlet14_Upload extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String file=req.getParameter("file");
        // file==null 原因是以字符串形式去取取文本是取不到的,应该以流的形式去取

        //字节流
        InputStream inputStream = req.getInputStream();

        /*
        //这里先注释掉,否则后面读取不到inputStream
        int temp = 0;
        while ((temp = inputStream.read()) != -1) {
            //读取图片的二进制流---打印出来显示的都是数字
            System.out.println(temp);
        }
        */


        //InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        //Reader reader = new InputStreamReader(inputStream);//不加UTF-8乱码但是后续写入文件就不乱码了
        Reader reader = new InputStreamReader(inputStream,"UTF-8");
        BufferedReader bufferedReader = new BufferedReader(reader);
        //通过输出流将数据输出到本地硬盘存储起来
        //获取文件夹绝对路径--out的绝对路径相关
        //String path = req.getServletContext().getRealPath("/file/copy.jpg");
        String path = req.getServletContext().getRealPath("/file/copy.txt");
        OutputStream outputStream = new FileOutputStream(path);
        //WebDemo\out\artifacts\ServeletPractice_war_exploded\file\copy.txt (系统找不到指定的路径。)
        //需要提前创建好文件夹file

        Writer writer = new OutputStreamWriter(outputStream);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);

        String str = "";
        while ((str = bufferedReader.readLine()) != null) {
            System.out.println(str);//打印
            bufferedWriter.write(str);//输出保存
        }
        /*String str_reaad = "";
        while ((str_reaad=bufferedReader.readLine())!=null) {
            System.out.println(str_reaad);
        }
        String str_write = "";
        while ((str_write=bufferedReader.readLine())!=null) {
            System.out.println(str_write);
        }*/
        bufferedWriter.close();
        writer.close();
        bufferedReader.close();
        reader.close();
        inputStream.close();
        //
        //
    }
}

二、推荐的upload file逻辑

下载commons-fileupload-1.4.jar和commons-io-2.11.0.jar引用到工程中



Servlet14_Upload.java


package com.test.app;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author:
 * @date:2022/1/18
 * @description:
 */
@WebServlet("/servlet14_Upload")
public class Servlet14_Upload extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

            List<FileItem> fileItemList = servletFileUpload.parseRequest(req);
            System.out.println(fileItemList);

            for (FileItem fileItem : fileItemList) {
                System.out.println(fileItem.getName());
                System.out.println(fileItem.getFieldName());//获取表单提交时候的name属性值
                //如果fileItem.isFormField()==true表示它是一个文本,浏览器中可能体现为一个输入框
                if (fileItem.isFormField()) {
                    String name = fileItem.getFieldName();
                    String value = fileItem.getString("UTF-8");
                    System.out.println(name + "\t" + value);
                    //如果fileItem.isFormField()==true表示它是一个文件
                } else {

                    //1、整行读取是读不出换行符号的
                    //2、按字节读取可以读出换行符
                    //3、按字符读取的时候如果遇到图片文件,由于不是按照字节读取,图片数据的内部结构被破坏。
                    String fileName = fileItem.getName();
                    long size = fileItem.getSize();
                    System.out.println(fileName + ":" + size + "Byte");
                    String path = req.getServletContext().getRealPath("file/" + fileName);
                    InputStream inputStream = fileItem.getInputStream();
                    OutputStream outputStream = new FileOutputStream(path);
                    int temp = 0;
                    while ((temp = inputStream.read()) != -1) {
                        outputStream.write(temp);
                    }
                    outputStream.close();
                    inputStream.close();
                    System.out.println("上传成功");


                    /**
                     String fileName = fileItem.getName();
                     long size = fileItem.getSize();
                     System.out.println(fileName + ":" + size + "Byte");
                     String path = req.getServletContext().getRealPath("file/" + fileName);
                     InputStream inputStream = fileItem.getInputStream();
                     OutputStream outputStream = new FileOutputStream(path);
                     Reader reader = new InputStreamReader(inputStream);
                     BufferedReader bufferedReader = new BufferedReader(reader);
                     Writer writer = new OutputStreamWriter(outputStream);
                     BufferedWriter bufferedWriter = new BufferedWriter(writer);
                     String temp = null;
                     while ((temp = bufferedReader.readLine()) != null) {
                     bufferedWriter.write(temp);

                     }
                     //整行读取是读不出换行符号的
                     //按字节读取可以读出换行符
                     bufferedWriter.close();
                     writer.close();
                     outputStream.close();
                     bufferedReader.close();
                     reader.close();
                     inputStream.close();
                     System.out.println("上传成功");
                     */
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }

    protected void doPost_not_recommened(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String file=req.getParameter("file");
        // file==null 原因是以字符串形式去取取文本是取不到的,应该以流的形式去取

        //字节流
        InputStream inputStream = req.getInputStream();

        /*
        int temp = 0;
        while ((temp = inputStream.read()) != -1) {
            //读取图片的二进制流---打印出来显示的都是数字
            System.out.println(temp);
        }
        */


        //InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        //Reader reader = new InputStreamReader(inputStream);//不加UTF-8乱码但是后续写入文件就不乱码了
        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(reader);
        //通过输出流将数据输出到本地硬盘存储起来
        //获取文件夹绝对路径--out的绝对路径相关
        //String path = req.getServletContext().getRealPath("/file/copy.jpg");
        String path = req.getServletContext().getRealPath("/file/copy.txt");
        OutputStream outputStream = new FileOutputStream(path);
        //WebDemo\out\artifacts\ServeletPractice_war_exploded\file\copy.txt (系统找不到指定的路径。)
        //需要提前创建好文件夹file

        Writer writer = new OutputStreamWriter(outputStream);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);

        String str = "";
        while ((str = bufferedReader.readLine()) != null) {
            System.out.println(str);
            bufferedWriter.write(str);
        }
        /*String str_reaad = "";
        while ((str_reaad=bufferedReader.readLine())!=null) {
            System.out.println(str_reaad);
        }
        String str_write = "";
        while ((str_write=bufferedReader.readLine())!=null) {
            System.out.println(str_write);
        }*/
        bufferedWriter.close();
        writer.close();
        bufferedReader.close();
        reader.close();
        inputStream.close();
        //
        //
    }
}



index15_upload.jsp


<%--
  Created by IntelliJ IDEA.
  User: Admin
  Date: 2022/1/18
  Time: 15:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>upload</title>
</head>
<body>
<%--<form action="servlet14_Upload" method="get">--%>
<%--<form action="servlet14_Upload" method="post">--%>
<form action="servlet14_Upload" method="post" enctype="multipart/form-data">

    上传文件:<input type="file" name="file"> <br/>
    上传图片:<input type="file" name="img"> <br/>
    上传文本:<input type="file" name="text"> <br/>
    上传desc:<input type="text" name="desc"> <br/>
    <input type="submit" value="提交上传的文件"> <br/>
</form>
<p>可以提交文件、图片等文件</p>
<p>如果提交的txt文件后台直接读取txt文件中的字符串</p>
</body>
</html>



版权声明:本文为qq_44885775原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。