普通表单提交的是文本类型的数据,但视频、图片文件不是文本类型;此时需要使用 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 请求的最大大小限制
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”



