SpringMVC MVC文件上传

引入依赖

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

配置web.xml

设置允许上传文件大小

  <!--配置控制器-->
  <servlet>
    <servlet-name>mvcServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--配置文件,读取配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc2.xml</param-value>
    </init-param>
    <!--配置文件上传大小控制-->
    <multipart-config>
      <max-file-size>20848820</max-file-size>
      <max-request-size>418018841</max-request-size>
      <file-size-threshold>1048576</file-size-threshold>
    </multipart-config>
  </servlet>

Part方式单文件上传

Controller
@Controller
@RequestMapping("/upload")
public class UploadController {
    @GetMapping("/jump")
    public String jump() {
        return "upload/add";
    }
    //part上传--单文件
    //文件上传 必须用post方式
    @PostMapping("/test1")
    public String uploadPartOne(HttpServletRequest request) throws ServletException, IOException {
        //从request对象中 获取 值(文件)
        //request.getPart("页面表单提交的name值")
        Part pic = request.getPart("img_pic");
        //文件存储到哪里
        String realPath = request.getServletContext().getRealPath("/");
        System.out.println(realPath);
        //获取文件名,上传的文件名称
        String fileName = pic.getSubmittedFileName();
        pic.write(realPath + fileName);
        return "success";
    }

}
jsp
<form method="post" action="/mvc/upload/test1" enctype="multipart/form-data">
	<div class="form-control-file">
		<input type="file" name="img_pic">
	</div>
	<div class="form-control">
		<input type="submit" class="bg-success" value="上传">
	</div>
</form>

Part方式多文件上传

Controller

@PostMapping("/test2")
    public String upload2(HttpServletRequest request) throws ServletException, IOException {
        //获取 所有的文件
        Collection<Part> parts = request.getParts();
        //文件存储路径
        String realPath = request.getServletContext().getRealPath("/") + "imgs/";
        //循环 获取
        parts.forEach( part -> {
            String fileName = part.getSubmittedFileName();
            try {
                part.write(realPath +fileName);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        return "upload/success";
    }

jsp

<form method="post" action="/mvc/upload/test2" enctype="multipart/form-data">
    <div class="form-control-file">
        <input type="file" name="img_pic" multiple>
    </div>
    <div class="form-control">
        <input type="submit" class="btn btn-success" value="上传">
    </div>
</form>

MVC方式单文件上传

导入依赖

  <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.4</version>
        </dependency>

修改配置文件

<!--防止文件中文乱码-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>

Controller

	@Autowired
    HttpSession session;

    @PostMapping("/test3")
    public String upload3(MultipartFile img_pic) throws IOException {
        if (img_pic!=null && !img_pic.isEmpty()){
            doUpload(img_pic);
        }
        return "upload/success";
    }
private void doUpload(MultipartFile multipartFile){
        //获取文件名
        String filename = multipartFile.getOriginalFilename();
        //获取保存路径
        //D:\tempFolder\mvcdemo1\target\mvcdemo\imgs\
        String realPath = session.getServletContext().getRealPath("/imgs/");
        //加一层文件夹
        //D:\tempFolder\mvcdemo1\target\mvcdemo\imgs\2024/07/02/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        realPath += simpleDateFormat.format(new Date());
        //自动创建文件夹
        File file = new File(realPath);
        if (!file.exists()) {
            //如果 文件夹不存在,创建文件夹
            file.mkdirs();
        }

        //获取文件名
        //随机获取文件名
        //保存文件的核心代码
        String allPath = realPath + RandomUtil.getFileName(filename);
        try {
            multipartFile.transferTo(new File(allPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
public class RandomUtil {

    private RandomUtil() {
    }

    private final static String pool =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    //传入数字,返回对应长度的随机字符串
    public static String getString(int length){
        if (length <= 0){
            throw new IllegalArgumentException("参数异常,不能小于等于0");
        }
        StringBuilder result = new StringBuilder();
        for (int i=0;i<length;i++){
            int index = ThreadLocalRandom.current().nextInt(pool.length());
            char c = pool.charAt(index);
            result.append(c);
        }
        return result.toString();
    }

    //生成随机的文件名
    public static String getFileName(String filename){
        //abc.jpg
        int lastindex = filename.lastIndexOf(".");
        if (lastindex == -1){
            throw new IllegalArgumentException("文件名异常,没有文件类型");
        }
        //文件的类型
        String filetype = filename.substring(lastindex + 1);
        //文件名上加上时间戳
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = simpleDateFormat.format(new Date());
        String name = getString(5)+time+"."+filetype;
        return name;
    }
}

MVC方式多文件上传

    @PostMapping("/test")
    public String upload4(MultipartFile[] img_pic) {
        if (img_pic != null && img_pic.length > 0) {
            for (MultipartFile file : img_pic){
                if (!file.isEmpty()){
                    doUpload(file);
                }
            }
        }
        return "upload/success";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值