java web文件上传

实现文件上传的服务器端方法:

SmartUpload.jar –过时。
a servlet3.0 的注解.mutipart
b apache common-file-upload组件
c springmvc框架(依赖于上面)

文件上传的案例:

1 单文件上传
2 多文件上传
3 混合表单上传
4 Ajax上传。

common-file-upload文件上传

upload.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="FileUploadServlet" enctype="multipart/form-data" method="post">
        请选择要上传的文件:<br/><input type="file" name="file"/><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

//获取工厂
        FileItemFactory factory = new DiskFileItemFactory();
        //获取上传文件工具类
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        String newFileName = null;
        try {
            List<FileItem> list = upload.parseRequest(request);

            for(FileItem item:list){
                //请求参数的name
                System.out.println(item.getFieldName());
                //文件名称
                System.out.println(item.getName());
                //是否是普通表单
                System.out.println(item.isFormField());
                //文件大小
                System.out.println(item.getSize());
                if(!item.isFormField()){
                    //存储到服务器的web工程本地img子目录中
                    String realPath = request.getServletContext().getRealPath("");
                    int pos = item.getName().lastIndexOf(".");
                    newFileName = UUID.randomUUID().toString().replaceAll("-","")
                            +item.getName().substring(pos);
                    System.out.println(newFileName);
                    String filePath = realPath + "img/" + newFileName;
                    System.out.println("存储路径 :"+filePath);
                    File file = new File(filePath);
                    item.write(file);
                }
            }
        } catch (Exception e) {
            response.getWriter().println("文件上传出错:"+e.getMessage());
        }
        request.setAttribute("msg","文件上传成功!");
        request.setAttribute("filename",newFileName);
        request.getRequestDispatcher("show_one.jsp").forward(request,response);

改进文件命名规则

 //获取工厂
        FileItemFactory factory = new DiskFileItemFactory();
        //获取上传文件工具类
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解决文件中文名乱码问题
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> list=upload.parseRequest(request);
            for (FileItem item:list){
                //请求参数的name
                System.out.println(item.getFieldName());
                //文件名称
                System.out.println(item.getName());
                //是否是普通表单
                System.out.println(item.isFormField());
                //文件大小
                System.out.println(item.getSize());
                if (!item.isFormField()){
                    //存储服务器的web工程本地img子目录中
                    String realPath=request.getServletContext().getRealPath("");
                    //拿到后缀名
                    int pos=item.getName().indexOf(".");
                    //通过UUID类生成不同的id
                    String newFileName= UUID.randomUUID()+item.getName().substring(pos);
                    String filePath=realPath+"/img/"+newFileName;
                    System.out.println("存储路径:"+filePath);
                    File file=new File(filePath);
                    item.write(file);
                }
            }
        } catch (Exception e) {
           response.getWriter().println("文件上传出错:"+e.getMessage());
        }
        response.getWriter().println("文件上传成功!");
        response.getWriter().flush();
        response.getWriter().close();

文件回显

//获取工厂
        FileItemFactory factory = new DiskFileItemFactory();
        //获取上传文件工具类
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解决文件中文名乱码问题
        upload.setHeaderEncoding("utf-8");
        String newFileName=null;
        try {
            List<FileItem> list=upload.parseRequest(request);
            for (FileItem item:list){
                //请求参数的name
                System.out.println(item.getFieldName());
                //文件名称
                System.out.println(item.getName());
                //是否是普通表单
                System.out.println(item.isFormField());
                //文件大小
                System.out.println(item.getSize());
                if (!item.isFormField()){
                    //存储服务器的web工程本地img子目录中
                    String realPath=request.getServletContext().getRealPath("");
                    //拿到后缀名
                    int pos=item.getName().indexOf(".");
                    //通过UUID类生成不同的id
                    newFileName= UUID.randomUUID()+"."+item.getName().substring(pos);
                    String filePath=realPath+"/img/"+newFileName;
                    System.out.println("存储路径:"+filePath);
                    File file=new File(filePath);
                    item.write(file);
                }
            }
        } catch (Exception e) {
           response.getWriter().println("文件上传出错:"+e.getMessage());
        }
        request.setAttribute("msg",newFileName+"文件上传成功");
        request.setAttribute("filename",newFileName);
       request.getRequestDispatcher("show_one.jsp").forward(request,response);

多文件上传

uploadMultiple.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="FileUploadServlet?method=uploadmultiple" enctype="multipart/form-data" method="post">
    请选择要上传的文件:<br/><input type="file" name="file"/><br>
    <input type="file" name="file"/><br>
    <input type="text" name="a" value="aa"><br>
    <input type="text" name="b" value="bb"><br>
    <input type="submit" value="上传">
</form>
</body>
</html>

uploadmultiple.java:

 //获取工厂
        FileItemFactory factory = new DiskFileItemFactory();
        //获取上传文件工具类
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解决文件中文名乱码问题
        upload.setHeaderEncoding("utf-8");
        String newFileName;
        List<String> newFileNames=new ArrayList<>();//存储新的文件名
        Map<String,String> formFieldMap=new HashMap<>();//存储非文件的参数
        try {
            List<FileItem> list=upload.parseRequest(request);
            for (FileItem item:list){
                //请求参数的name
                System.out.println(item.getFieldName());
                //文件名称
                System.out.println(item.getName());
                //是否是普通表单
                System.out.println(item.isFormField());
                //文件大小
                System.out.println(item.getSize());
                //文件项
                if (!item.isFormField()){
                    //存储服务器的web工程本地img子目录中
                    String realPath=request.getServletContext().getRealPath("");
                    //拿到后缀名
                    int pos=item.getName().indexOf(".");
                    //通过UUID类生成不同的id
                    newFileName= UUID.randomUUID()+"."+item.getName().substring(pos);
                    String filePath=realPath+"/img/"+newFileName;
                    System.out.println("存储路径:"+filePath);
                    File file=new File(filePath);
                    item.write(file);
                    newFileNames.add(newFileName);
                }else{//非文件项
                    String key=item.getFieldName();//参数名
                    String value=item.getString();//参数值
                    formFieldMap.put(key,value);//存储在map中
                }
            }
        } catch (Exception e) {
            response.getWriter().println("文件上传出错:"+e.getMessage());
        }
        request.setAttribute("msg",newFileNames.size()+"个文件上传成功");
        request.setAttribute("filenames",newFileNames);
        request.setAttribute("formfieldmap",formFieldMap);
        request.getRequestDispatcher("show_multiple.jsp").forward(request,response);

show_multiple.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${msg}<br>
    <c:forEach items="${filenames}" var="filename">
        <img src="img/${filename}" width="100px" height="200px"><br>
    </c:forEach>
    其他参数:
    <c:forEach items="${formfieldmap.entrySet()}" var="e">
         ${e.getKey()}=${e.getValue()}&nbsp;
    </c:forEach>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java后端指南

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值