apache的fileupload文件上传快速入门demo

入门demo

表单:

需要的jar包

commons-fileupload-1.3.1.jar
commons-io-2.4.jar

 

form表单中:

注意必须有enctype,且值必须为multipart/form-data 提交方式也必须为post,因为get请求大小有限制,且不安全

enctype="multipart/form-data"

method="post" 


 servlet代码:

package com.yellow.web.servlet;

import org.apache.commons.fileupload.FileItem;
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.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@WebServlet("/upload04")
public class UploadServlet04 extends HttpServlet {

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断请求是否支持文件上传
        boolean multipartContent = ServletFileUpload.isMultipartContent(req);
        if (multipartContent) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //启用临时文件的大小,并设置临时文件路径
            //1MB启用
            factory.setSizeThreshold(1024 * 1024);
            String temppath = req.getServletContext().getRealPath("/temp");
           // System.out.println("temppath = " + temppath);
            File file = new File(temppath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //临时文件的存储路径
            factory.setRepository(file);

            ServletFileUpload sfu = new ServletFileUpload(factory);
            try {
                List<FileItem> items = sfu.parseRequest(req);
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        //说明是文件上传的item
                        String fileName = item.getName();
                        //若文件名中存在'\'截取,获得字串
                        fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
                        //防止文件重名使用uuid生成文件名称
                        fileName = UUID.randomUUID() + "_" + fileName;
                        String uploadpath = req.getServletContext().getRealPath("/upload");
                        //System.out.println("uploadpath = " + uploadpath);
                        //获取当前系统时间,以文件目录来存储上传的文件
                        LocalDate now = LocalDate.now();
                        int year = now.getYear();
                        int month = now.getMonthValue();
                        int day = now.getDayOfMonth();
                        uploadpath=uploadpath+"/"+year+"/"+month+"/"+day;
                        File _file = new File(uploadpath);
                        if(!_file.exists())_file.mkdirs();
                        File path = new File(uploadpath, fileName);
                        if (!path.exists()) {
                            path.createNewFile();
                        }
                        item.write(path);
                        //手动删除临时文件
                        item.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

html页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传快速入门</title>
</head>
<body>
<form action="/upload04" enctype="multipart/form-data" method="post">
    <table align="center" border="1">
        <tr>
            <td><input type="file" name="photo"><br></td>
        </tr>
        <tr>
            <td align="center"><input type="submit" value="上传"></td>
        </tr>
    </table>
</form>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值