SpringMvc 文件上传

版权声明:早起签到群:642179511 [2018我们要早起不赖床] https://blog.csdn.net/qq_36238595/article/details/79879826

上传文件的表单必须指定为:

enctype="multipart/form-data" 
method="post"

springmvc.xml配置

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
    </bean>

用form表单提交

前台

<form id="loadForm" action="${path}/upload" enctype="multipart/form-data" method="post">
    <input name="fileInput" type="file">
    <input  type="button" onclick="upload()" value="提交"/>
</form>

控制器

    @RequestMapping(value="upload", method = RequestMethod.POST)
    public String upload(
            HttpSession session,
            @RequestParam("fileInput") MultipartFile file) throws IOException {

        String path = session.getServletContext().getRealPath("/static/img");
        String fileName = file.getOriginalFilename();
        file.transferTo(new File(path, fileName));
        System.out.println(path+","+fileName);
        return "success";
    }

ajax提交

前台代码


<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<form id="loadForm" action="${path}/upload" enctype="multipart/form-data" method="post">
    <input name="fileInput" type="file">
    <input  type="button" onclick="upload()" value="提交"/>
</form>

<script>
    function upload(){
        var formData = new FormData($( "#loadForm" )[0]);
        $.ajax({
            url: '${path}/upload',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (msg) {
                alert(msg);
            }
        });
    }
</script>

控制器还是一样的

阅读更多
换一批

没有更多推荐了,返回首页