Fork me on GitHub

springMVC的文件上传

首先需要导入jar包

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

将表单的将enctype设置为 multipart/form-data(把文件以二进制数据发送给服务器)。并且method需要设置为POST

<form action="${pageContext.request.contextPath}/upload1" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
    <input type="submit" name="upload">
  </form>

controller层:

package com.zx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: com.zx.controller
 * @version: 1.0
 */
@Controller
public class UploadController {
    //方式一:
    /*
    CommonsMultipartFile 的 常用方法: 
      String getOriginalFilename():获取上传文件的原名
      InputStream getInputStream():获取文件流 
      void transferTo(File dest):将上传文件保存到一个目录文件中
    */
    @RequestMapping("/upload1")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //判断文件名是否为空,为空的话就重定向到首页
        if("".equals(originalFilename)){
            return "redirect:/index.jsp";
        }
        System.out.println("上传文件名:"+originalFilename);

        //上传路径保存的位置
        String realPath = request.getServletContext().getRealPath("/upload");
        File filePath = new File(realPath);
        //如果文件路径不存在就创建
        if (!filePath.exists()){
            filePath.mkdir();
        }

        InputStream is = file.getInputStream();//文件输入流
        FileOutputStream os = new FileOutputStream(new File(filePath, originalFilename));//文件输出流

        //文件写出
        int len=0;
        byte[] buffer = new byte[1024];
        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        is.close();
        return "redirect:/index.jsp";
    }
    
    //方式二:利用CommonsMultipartFile的transferTo方法进行文件转储
    
    @RequestMapping("/upload2")
    public String upload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
        //上传文件的路径
        String realPath = request.getServletContext().getRealPath("/upload");
        File filePath = new File(realPath);
        if (!filePath.exists()){
            filePath.mkdir();
        }

        //通过CommonsMultipartFile的transferTo方法进行文件转储
        //file.getOriginalFilename() 源文件名
        file.transferTo(new File(filePath+"/"+file.getOriginalFilename()));
        //重定向到首页
        return "redirect:/index.jsp";
    }
}

文件上传的bean配置

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 请求的编码格式-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 上传文件的大小限制,单位为字节(10485760=1024*1024*10=10M) 可自定义大小-->
        <property name="maxUploadSize" value="10485760"/>
    </bean>

注意:文件会保存在项目的out目录中!

posted @ 2021-03-09 10:56  雾深  阅读(99)  评论(0编辑  收藏  举报