栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring MVC-----文件上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring MVC-----文件上传

1.multipart请求

普通表单提交的是文本类型的数据,但视频、图片文件不是文本类型;此时需要使用 multipart 请求将表单字段分成相应的块,每个块都有自己的数据类型。对于上传字段对应的块,数据类型就可以是二进制。

2.配置 multipart resovler

在Servlet3.0 + Spring 3.1+的环境里可以使用StandardServletMultipartResolver 来解析multipart 请求。
在spring mvc 的配置文件中配置 StandardServletMultipartResolver Bean


由于 StandardServletMultipartResolver需要依赖Servlet3.0, 所以需要在 web.xml里的DispatchServlet 中配置


        dispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:application.xml
        
        1
        
            
            5245
            44243
        
    

location:上传文件将被存储的目录位置
max-file-size:上传文件的最大大小限制
max-request-size: multipart/form-data 请求的最大大小限制

3.Controller
package com.iran.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.MultipartFile;

import java.io.File;
import java.io.IOException;


@Controller
public class UploadController {

   @RequestMapping("/upload")
   public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("username") String username) {
       System.out.println(username);
       if (!file.isEmpty()) {
           // 文件存放的位置
           String root = "///";
           File fileRoot = new File(root);
           if (!fileRoot.exists()) {
               fileRoot.mkdir();
           }
           String uploadFile = root + file.getOriginalFilename();
           File file1 = new File(uploadFile);
           try {
               file.transferTo(file1);
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return "success";
   }
}

4.页面

<%--
  Created by IntelliJ IDEA.
  User: 糖人
  Date: 2021/10/4
  Time: 9:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    文件上传


    
用户名:

文件上传:

注意必须声明:enctype=“multipart/form-data”

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/309906.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号