JavaWeb(六)文件传输

十三、文件传输

数据可以通过管道传输,做一些IO操作,就可以实现文件传输,为了方便我们进行文件传输,可以导入两个包

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

13.1 文件下载

在6.6.1 里面说过,可以去看看之前的那篇博客。https://blog.csdn.net/yangsf_/article/details/123980675?spm=1001.2014.3001.5501

13.2 文件上传

前端页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>文件上传</title>
  </head>
  <body>
    <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
      姓名:<input type="text" name="name">
      <br>
      <p>选择文件:<input type="file" name="file1"></p>
      <p>选择文件:<input type="file" name="file1"></p>

      <p><input type="submit" value="上传"></p>
    </form>
  </body>
</html>

servlet处理表单,实现文件上传:

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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            // 检查是否有文件上传请求
            if (ServletFileUpload.isMultipartContent(req)) {

//      ====================    文件上传到哪里?    ====================
                // 创建保存文件的文件夹
                String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
                File uploadFile = new File(uploadPath);
                if (!uploadFile.exists()) {
                    uploadFile.mkdir();
                }

                // 创建临时文件存放目录
                String tmpPath = this.getServletContext().getRealPath("/WEB-INF/temp");
                File tempFile = new File(tmpPath);
                if (!tempFile.exists()) {
                    uploadFile.mkdir();
                }

//      ====================    上传前准备   ====================

                //
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // 超过这个大小则作为临时文件
                factory.setSizeThreshold(1024*1024*10);
                // 临时文件存放位置
                factory.setRepository(tempFile);
                // 可以这样  DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024*10, tempFile);

                // 文件上传处理对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);

                // 将所有的表单输入存到List中
                List<FileItem> fileItems = fileUpload.parseRequest(req);

//      ====================    文件上传    ====================
                // 遍历每一个表单输入
                for (FileItem item : fileItems) {
                    // 判断是否是普通表单输入,不是就上传
                    if (item.isFormField()) {
                        // 获得前端 input 的 name 属性值
                        String name = item.getFieldName();
                        String value = item.getString("UTF-8");
                        System.out.println(name + ":" + value);
                    } else {
                        // 获取文件上传路径
                        String uploadFileName = item.getName();
                        System.out.println("文件名:" + uploadFileName);

                        // 文件名是否合法
                        if (uploadFileName.trim().equals("")) {
                            continue;
                        }

                        // 获取文件名
                        String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                        // 获取文件类型
                        String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                        System.out.println("文件信息:\n文件名:" + fileName + "文件类型:" + fileExtName);
                        // uuid是随机生成的一段码,我们用它来防止文件名重复
                        String uuidPath =  UUID.randomUUID().toString();

                        /*
                        // 可以为每一个文件创建一个文件夹
                        String realPath = uploadPath + "/" + uuidPath;
                        File realPathFile = new File(realPath);
                        if (!realPathFile.exists()) {
                            realPathFile.mkdir();
                        }
                        */

                        InputStream inputStream = item.getInputStream();
                        FileOutputStream fos = new FileOutputStream(uploadPath + "/" + fileName);
                        byte[] buffer = new byte[1024*1024];
                        int len = 0;
                        while ((len = inputStream.read(buffer)) > 0) {
                            fos.write(buffer);
                        }
                        // 释放资源
                        fos.close();
                        inputStream.close();
						// 删除临时的文件,不然磁盘中会出现两个文件
                        item.delete();

                    }
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值