侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 747 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

SpringMVC(9)之文件上传

zze
zze
2017-12-23 / 0 评论 / 0 点赞 / 354 阅读 / 2457 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

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";
    }
}
0

评论区