【SpringMVC】文件上传

我与影子孤独终老i 提交于 2020-01-10 10:57:24

1.导包&配置

导包

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

别忘了Put into Output Root
在这里插入图片描述
配置
WEB-INF/dispatcher-servlet.xml

<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="5242880"/>
</bean>

2.写upload.jsp

上传文件很重要的一点,form表单的属性enctype="multipart/form-data"设置。

<form method="post" action="/upload" enctype="multipart/form-data">

upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>upload</title>
    <link rel="stylesheet" href="/static/css/formcss.css"/>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <table class="tb">
        <input type="text" hidden name="id" value="${user.id}">
        <tr>
            <td>文件名:</td>
            <td><input type="text" name="fileName" value="${user.name}"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="file" name="uploadFile"></td>
        </tr>
        <tr>
            <td><input type="submit" value="上传"></td>
            <td><input type="reset" value="重置"></td>
        </tr>
    </table>
</form>
</body>
</html>

如果使用ajax请求上传文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>upload</title>
    <link rel="stylesheet" href="/static/css/formcss.css"/>
    <script src="/static/js/jquery-3.4.1.min.js"></script>
</head>
<body>
<form id="up_form" enctype="multipart/form-data">
    <table class="tb">
        <tr>
            <td>文件名:</td>
            <td><input type="text" name="fileName" value=""></td>
        </tr>
        <tr>
            <td colspan="2"><input type="file" name="uploadFile"></td>
        </tr>
        <tr>
<%--            <td colspan="2"><button onclick="upload()">上传</button></td>--%>
            <td colspan="2"><input type="button" onclick="upload()" value="上传"></td>
        </tr>
    </table>
</form>
<script>
    function upload() {
        let data=new FormData(document.getElementById("up_form"));
        $.ajax({
            url: "/upload",
            type: "post",
            data: data,
            cache: false,
            contentType: false,
            processData : false, // 使数据不做处理
            success: (data)=>{
                alert(data)
            }
        })
    }
</script>
</body>
</html>

3.写@Controller UploadController

@Controller
public class UploadController {


    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody//返回json格式
    public String upload(String fileName, MultipartFile uploadFile
    , HttpServletRequest request){
        //保存文件
        return "upload success.";
    }
}

4.UploadController保存文件

	@PostMapping("/upload")
    @ResponseBody
    public String upload(String fileName, MultipartFile uploadFile
    , HttpServletRequest request){
        //1.文件名处理,避免与本地重复
        String theName="";
        String originalFilename = uploadFile.getOriginalFilename();
        //获取文件类型,很重要,不做这一步保存的文件类型不明无法打开
        String type=originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid= UUID.randomUUID().toString();
        if(fileName.equals("")){
            theName=uuid+"_"+originalFilename;
        }else {
            theName=fileName+"_"+uuid+type;
        }
        //2.找到upload路径
        ServletContext servletContext = request.getServletContext();
        //按日期建文件夹存储文件
        String date=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String realPath = servletContext.getRealPath("/upload/"+date);
        System.out.println(realPath);
        File path=new File(realPath);
        //3.判断路径是否存在
        if(!path.exists()){
            path.mkdirs();
        }
        try {
            //4.保存文件
            uploadFile.transferTo(new File(path,theName));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return "upload failed.";
        }
        return "upload success.";
    }

效果:
在这里插入图片描述
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!