javaWeb实现简单文件上传

 更新时间:2022年06月22日 10:35:28   作者:学以致用HT  
这篇文章主要为大家详细介绍了JAVAWeb实现简单文件上传,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了javaWeb实现简单文件上传的具体代码,供大家参考,具体内容如下

1.先导入两个包:commons-fileupload-1.3.3.jar,commons-io-2.6.jar。

2.前端页面代码

<form action="upLoadfile.do" method="post"
        enctype="multipart/form-data">
        <input type="text" name="username" /><br> 
        <input type="file" name="userimg" /><br> 
        <input type="submit" value="提交" />
</form>

2.Servlet代码

package com.uploadtest.upload;
 
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
/**
 * Servlet implementation class upLoadfile
 */
@WebServlet("/upLoadfile.do")
public class upLoadfile extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public upLoadfile() {
        super();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String saveFileName = ""; //
        String oldFileName = ""; // 直接由item.getNam()获取的文件名,有可能获取的是路径,也为了避免重名覆盖,所以要对它进行处理
        String newFileName = ""; // 对源文件名进行处理后的名字
        // 借助工具解析commons-fileupload smartupload(在项目中导入了jar包)
        // 判断传递的是否是文件类型,判断form的enctype的属性值是否是multipart/form-data
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            // 创建FileItem对象的工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 获取Servlet上下文
            ServletContext servletContext = null;
            servletContext = this.getServletConfig().getServletContext();
            // 获取临时文件夹
            String str = "javax.servlet.context.tempdir";
            File repository = (File) servletContext.getAttribute(str);
            factory.setRepository(repository);
            // 创建文件上传处理器
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 解决中文乱码
            upload.setHeaderEncoding("utf-8");
            // 解析request获取上传的参数
            try {
                // 使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
                List<FileItem> items = upload.parseRequest(request);
                // 解决上传文件名的中文乱码
                upload.setHeaderEncoding("UTF-8");
                // 处理参数
                for (FileItem item : items) {
                    // 判断是否为Form的表单域,即判断是否为普通的数据,若不是则为文件。
                    if (item.isFormField()) {
                        String name = item.getFieldName();
                        // 解决普通输入项的数据的中文乱码问题
                        String value = item.getString("UTF-8");
                        // value = new String(value.getBytes("iso8859-1"),"UTF-8");
                        //System.out.println(name + "=" + value);
                    } else {
                        // 设置上传单个文件的大小的最大值,目前是设置为1024*1024*10字节,也就是10MB
                        upload.setFileSizeMax(1024 * 1024 * 10);
                        // 写入文件
                        // 此处本项目在服务器中的路径,为绝对路径,也可以根据需要存入到其他路径
                        String rootPath = servletContext.getRealPath("//");
                        // File.separator(相当于添加了一个分隔符),在Windows下的路径分隔符(\)和在Linux下的路径分隔符(/)是不一样的,当直接使用绝对路径时,跨平台会报异常                        
                        String savePath = rootPath + File.separator + "upload";
                        /*  此处我是将文件保存在服务器上的,这样的话如果重写部署一次服务器,之前上传的文件就会删除
                          如果想永久保存上传的文件,可以设置一个其他绝对路径,如:E:\eclipse-workspace\JAVAWeb\JSPUploadTest\WebContent\fileByupload。*/                         
                        // String savePath = "E:\\eclipse-workspace\\JAVAWeb\\JSPUploadTest\\fileByupload";
 
                        File fileSaveFolder = new File(savePath);
                        // 如果不存在该文件夹则创建
                        if (!fileSaveFolder.exists()) {
                            fileSaveFolder.mkdir();
                        }
                        oldFileName = item.getName();
                        newFileName = processFileName(oldFileName);
                        saveFileName = savePath + File.separator + newFileName;
                        // 存储文件
                        File uploadedFile = new File(saveFileName);
                        item.write(uploadedFile);
                    }
                }
                request.setAttribute("message", "文件上传成功!");
            } catch (FileUploadBase.FileSizeLimitExceededException e) {
                e.printStackTrace();
                request.setAttribute("message", "照片大小不能超过10M");
                request.getRequestDispatcher("Show.jsp").forward(request, response);
                return;
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            request.setAttribute("saveFileName", saveFileName);
            request.setAttribute("newFileName", newFileName);
            request.getRequestDispatcher("Show.jsp").forward(request, response);
        }
    }
 
    // 对文件名进行处理
    private String processFileName(String oldFileName) {
        // 补充:对于 item.getName()有的浏览器会返回文件名,而有的浏览器会返回“路径”+“文件名”,针对后者我们需要通过“字符串截取”获取文件名
        // 例如会出现这样的情况:item.getName():C:\Users\Desktop\备忘录.txt
        String tempFileName = "";
        int index = oldFileName.lastIndexOf("\\");
        if (index != -1) {
            // subString(x)是从字符串的第x个字符截取
            tempFileName = oldFileName.substring(index + 1);
        }
        // 为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
        return UUID.randomUUID().toString() + "_" + tempFileName;
    }
}

3.图片展示

<p>${message}</p>
  <img id="picture" src="upload/${newFileName}" width="200px" height="200px" alt="不是图片">

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • springboot vue接口测试前后端实现模块树列表功能

    springboot vue接口测试前后端实现模块树列表功能

    这篇文章主要为大家介绍了springboot vue接口测试前后端实现模块树列表功能,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • 详解SpringBoot如何实现多环境配置

    详解SpringBoot如何实现多环境配置

    在实际的软件开发过程中,一个应用程序通常会有多个环境,pring Boot 提供了一个非常灵活和强大的方式来管理这些环境配置,下面就跟随小编一起学习一下吧
    2023-07-07
  • Spring Boot实现第一次启动时自动初始化数据库流程详解

    Spring Boot实现第一次启动时自动初始化数据库流程详解

    在现在的后端开发中,只要是使用关系型数据库,相信SSM架构(Spring Boot + MyBatis)已经成为首选,本文就以Spring Boot + MyBatis为例,使用MySQL作为数据库,完成数据库初始化功能,文中有详细的代码示例,需要的朋友可以参考下
    2023-05-05
  • spring缓存cache的使用详解

    spring缓存cache的使用详解

    这篇文章主要介绍了spring缓存cache的使用详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • Java Swing实现餐厅点餐系统源码(收藏版)

    Java Swing实现餐厅点餐系统源码(收藏版)

    这篇文章主要介绍了Java Swing实现餐厅点餐系统源码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • SpringBoot配置文件导入方法详细讲解

    SpringBoot配置文件导入方法详细讲解

    Spring Boot虽然是Spring的衍生物, 但默认情况下Boot是不能直接使用Spring的配置文件的, 我们可以通过两种方式导入Spring的配置
    2022-10-10
  • 详解Spring Security中权限注解的使用

    详解Spring Security中权限注解的使用

    这篇文章主要为大家详细介绍一下Spring Security中权限注解的使用方法,文中的示例代码讲解详细,对我们学习或工作有一定参考价值,需要的可以参考一下
    2022-05-05
  • java调用外部程序的方法及代码演示

    java调用外部程序的方法及代码演示

    这篇文章主要介绍了java调用外部程序的方法及代码演示的相关资料,需要的朋友可以参考下
    2023-03-03
  • Java基础之多线程方法状态和创建方法

    Java基础之多线程方法状态和创建方法

    Java中可以通过Thread类和Runnable接口来创建多个线程,下面这篇文章主要给大家介绍了关于Java基础之多线程方法状态和创建方法的相关资料,需要的朋友可以参考下
    2021-09-09
  • flatten-maven-plugin使用教程

    flatten-maven-plugin使用教程

    这篇文章主要介绍了flatten-maven-plugin使用,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07

最新评论