利用fileupload上传组件实现文件上传及保存到本地的js及servlet代码

一、js代码

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2020/7/12
  Time: 17:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>多文件上传</title>
    <script type="text/javascript">
        function addFileUploadDiv() {
            var divTag = document.getElementById("file");
            divTag.innerHTML += '<div>文件:<input type="file" name="file"><input type="button" value="删除" οnclick="deleteFileUploadDiv(this)"></div>';
        }
        function deleteFileUploadDiv(input) {
            var divTag = document.getElementById("file");
            divTag.removeChild(input.parentNode);
        }
    </script>
</head>
<body>
<form action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <div id="file">
        <div>文件:<input type="file" name="file"><input type="button" value="删除" onclick="deleteFileUploadDiv(this)"></div>
    </div>
    <input type="button" value="添加" onclick="addFileUploadDiv()">
    <input type="submit" value="提交">
</form>
</body>
</html>

二、servlet代码

package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
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.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class UploadServlet extends HttpServlet {
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        InputStream is = req.getInputStream();
//
//        byte[] buf = new byte[1024];
//
//        int len = 0;
//
//        while ((len = is.read(buf)) != -1){
//            String str = new String(buf,0,len,"utf-8");
//            System.out.println(str);
//        }
//
//        is.close();
//    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用fileupload组件解析request.getInputStream()
        //1.创建文件工厂
        FileItemFactory factory = new DiskFileItemFactory();
        //2.创建文件上传对象
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //3.限制单个文件大小
        sfu.setFileSizeMax(1024*1024*3);//单位是字节
        try {
            List<FileItem> items = sfu.parseRequest(req);
            for(FileItem item : items){
                if(item.isFormField()){//普通文本,若输入有中文,可在获取值时加上编码格式,避免乱码
                    System.out.println(item.getFieldName()+":"+item.getString("UTF-8"));
                }else{//文件
                    System.out.println("文件名:"+item.getName());
                    System.out.println("文件类型:"+item.getContentType());
                    System.out.println("文件大小:"+item.getSize());
//                    System.out.println("文件内容:"+item.getString());

                    //将文件保存到本地
                    //1.指定文件保存的路径
                    //添加一个日期目录
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    String dateStr = sdf.format(new Date());
                    //也可以将日期转为16进制
//                    String dateHexStr = Integer.toHexString(new Date().hashCode());
                    String path = req.getServletContext().getRealPath("upload/"+dateStr);
                    //2.创建文件夹
                    File dir = new File(path);
                    if(!dir.exists()){
                        dir.mkdirs();
                    }
                    //3.指定文件保存的名字
                    //获取后缀名
                    String suffix = item.getName().split("\\.")[1];
                    //拼接文件名
                    String fileName = UUID.randomUUID().toString()+"."+suffix;
                    //4.拼接文件保存路径
                    String fileSavePath = path+"\\"+fileName;
                    //5.保存文件
                    item.write(new File(fileSavePath));
                    //6.删除临时文件
                    item.delete();
                }
            }
        }catch (Exception e){e.printStackTrace();}
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值