本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

SpringMVC(9)之文件上传

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:


1、添加文件上传依赖:

<!-- pom.xml -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.2</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

2、配置多媒体处理器:

<!-- config/spring/springmvc.xml -->
<!--
配置多媒体处理器
注意:这里的 id 必须使用 multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--限制单次文件上传大小不超过 8m-->
    <property name="maxUploadSize" value="8388608"/>
</bean>

3、编写文件上传页面:

<!-- WEB-INF/jsp/fileupload.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>图片上传</title>
</head>
<body>
<form action="/fileupload" method="post" enctype="multipart/form-data">
    <input type="file" name="picFile">
    <input type="submit" value="上传">
</form>
</body>
</html>

4、编写文件上传服务端代码:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

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

@Controller
public class TestController {

    @RequestMapping(value = "fileupload", method = RequestMethod.GET)
    public String upload() {
        return "fileupload";
    }

    @RequestMapping(value = "fileupload", method = RequestMethod.POST)
    public String upload(Model model, MultipartFile picFile) throws IOException {
        File file = new File("D:/upload/" + picFile.getOriginalFilename());
        picFile.transferTo(file);
        model.addAttribute("msg", "上传成功");
        return "fileupload";
    }
}
# SpringMVC  

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×