资讯专栏INFORMATION COLUMN

SpringMVC文件上传

Karuru / 2438人阅读

摘要:为文件上传提供了直接的支持,这种支持是用即插即用的实现的。因此,的文件上传还需要依赖的组件。上传文件时,需要配置处理器文件上传文件上传是项目开发中最常见的功能。为了能上传文件,必须将表单的设置为,并将设置为。

SpringMVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。SpringMVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。因此,SpringMVC的文件上传还需要依赖Apache Commons FileUpload的组件。
1. 添加pom依赖
    
      commons-io
      commons-io
      2.3
    
    
      commons-fileupload
      commons-fileupload
      1.3.2
    
2. 配置文件上传bean

在spring mvc配置文件中增加一个文件上传bean。

    
    
        
    
3.文件上传
文件上传是项目开发中最常见的功能。为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器。

上传文件界面:upload_form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    文件上传






文件1:

文件2:

文件3:

用户名:

密码:

上传结果返回界面:upload_result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


    

上传结果为:${message}

注意:要提前创建好存储文件的文件夹,比如我的路径为:"D:staticResourcesTestimgupload"。

FileController.java

@Controller
@RequestMapping("/SpringMVCDemo1")
public class FileController {
    /**
     * 跳转到上传页面
     * @GetMapping 是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
     */
    @GetMapping("/gotoUploadForm")
    public String index() {
        return "/upload_form.jsp";
    }

    /**
     * 上传单个文件
     * 通过MultipartFile读取文件信息,如果文件为空跳转到结果页并给出提示;
     * 如果不为空读取文件流并写入到指定目录,最后将结果展示到页面
     * @param multipartFile
     * @PostMapping 是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。
     */
    @PostMapping("/upload")
    public String uploadSingleFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
        if (multipartFile.isEmpty()){
            request.setAttribute("message",  "Please select a file to upload "");
            return "/upload_result.jsp";
        }

        try {
            String contentType = multipartFile.getContentType();
            String originalFilename = multipartFile.getOriginalFilename();
            byte[] bytes = multipartFile.getBytes();
            System.out.println("上传文件名为-->" + originalFilename);
            System.out.println("上传文件类型为-->" + contentType);
            System.out.println("上传文件大小为-->"+bytes.length);

            //filePath为存储路径
            String filePath = "d:/staticResourcesTest";
            System.out.println("filePath-->" + filePath);
            //存储在staticResourcesTest下的imgupload文件夹下
            File parentPath = new File(filePath, "imgupload");
            System.out.println("上传目的地为-->"+parentPath.getAbsolutePath());
            try {
                File destFile = new File(parentPath,originalFilename);//上传目的地
                FileUtils.writeByteArrayToFile(destFile,multipartFile.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.setAttribute("message",  "You successfully uploaded "" + multipartFile.getOriginalFilename() + """);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/upload_result.jsp";
    }

    /**
     * 上传多个文件,同时接受业务数据
     * @param origFiles
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/uploadMultiFiles")
    public String uploadMultiFiles(@RequestParam("file") List origFiles, HttpServletRequest request, User user) {
        //User为实体类
        System.out.println("User=="+user);
        if (origFiles.isEmpty()) {
            request.setAttribute("message",  "Please select a file to upload "");
            return "/upload_result.jsp";
        }

        try {
            for (MultipartFile origFile : origFiles) {
                String contentType = origFile.getContentType();
                String fileName = origFile.getOriginalFilename();
                byte[] bytes = origFile.getBytes();
                System.out.println("上传文件名为-->" + fileName);
                System.out.println("上传文件类型为-->" + contentType);
                System.out.println("上传文件大小为-->"+bytes.length);

                String filePath = "d:/staticResourcesTest";
                System.out.println("上传目的地为-->"+filePath);
                try {
                    //上传目的地(staticResourcesTest文件夹下)
                    File destFile = new File(filePath,fileName);
                    FileUtils.writeByteArrayToFile(destFile,origFile.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            request.setAttribute("message",  "You successfully uploaded "");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "/upload_result.jsp";
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73859.html

相关文章

  • SpringMVC【参数绑定、数据回显、文件上传

    摘要:那我们就不用在每一个方法通过将数据传到页面。还能够配置该参数是否是必须的。方法的返回值有种重定向转发内部就是将数据绑定到域对象中的。注解能够将数据绑定到中也就是中,如果经常需要绑定到中的数据,抽取成方法来使用这个注解还是不错的。 前言 本文主要讲解的知识点如下: 参数绑定 数据回显 文件上传 参数绑定 我们在Controller使用方法参数接收值,就是把web端的值给接收到Cont...

    Flink_China 评论0 收藏0
  • SpringMVC 文件上传注意事项

    摘要:问题出现在没有熟练使用,采用上传文件主要注意几个事项。配置在文件中,增加一个处理文件上传同时要在文件夹下的下建立目录。控制器团队项目集合路径团队项目集合是上传文件的临时存储路径。这个步骤最关键,否则文件上传不上去。 简介 我在使用 idea 上传文件时遇到一些问题,费了好些时间,最后还是的队友来帮忙。 问题出现在没有熟练使用 IDE,采用 SpringMVC 上传文件主要注意几个事项。...

    aaron 评论0 收藏0
  • springmvc 接收上传图片并且存储至本地目录

    摘要:图片存储的方式为存储在虚拟目录下并返回虚拟目录的路径。如果是将开发的包直接部署在服务器中,则参考配置虚拟目录。 序言:项目环境 本次简单的demo是建立在springmvc框架上的,部署环境为tomcat,前段使用的bootstrap+jquery_file_upload组件。图片存储的方式为存储在虚拟目录下并返回虚拟目录的路径。建议先搭配好springmvc环境再继续参考本博客。没有...

    SimpleTriangle 评论0 收藏0

发表评论

0条评论

Karuru

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<