SpringMVC + Ajax文件上傳


前端

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ajax文件上傳練習</title>
    <script type="text/JavaScript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"></script>
</head>
<script type="text/javascript">
    $(function () {
        $("input[type='button']").click(function () {
            var formData = new FormData($("#upForm")[0]);
            $.ajax({
                type: "post",
                url: "${pageContext.request.contextPath}/upfile/upload",
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                success: function (data) {
                    alert(data);
                },
                error: function (response) {
                    console.log(response);
                    alert("上傳失敗");
                }
            });
        });
    });
</script>
<body>
    <form id="upForm" method="post" enctype="multipart/form-data">
        用戶名:<input type="text" name="userName" id="userName" /><br/>
        密碼:<input type="password" name="pwd" id="pwd" /><br/>
        <input type="file" name="image"><br/>
        <input type="button" value="提交" />
    </form>
</body>
</html>
注意: 14行的 data 別打成 date ;(手賤打錯,折騰半天) 
后台的Controller
@Controller
@RequestMapping("/upfile")
public class UpFileController {
    @RequestMapping("/upload")
    @ResponseBody
    public String getMsg(UserTest user,@RequestParam("image") CommonsMultipartFile file){
        System.out.println(user.getUserName());
        System.out.println(file.getOriginalFilename());
        return "接收成功";
    }
}
注意:第6行注解里的 image 必須和 文件控件的name屬性保持一致 <input type="file" name="image"> @RequestParam("image")
 SpringMVC的配置文件
<!-- 定義文件上傳解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <property name="defaultEncoding">
      <value>UTF-8</value>
   </property>
   <property name="maxUploadSize">
      <value>32505856</value><!-- 上傳文件大小限制為31M,31*1024*1024 -->
   </property>
   <property name="maxInMemorySize">
      <value>4096</value>
   </property>
</bean>

 

容易出現的錯誤

1.訪問后台成功,回來前端時404或是沒有信息返回

原因:Controller沒有加@ResponseBody 注解

2.前端提交信息,沒有到Controller,前端報錯400

Failed to load resource: the server responded with a status of 400 (Bad Request)

就是這個bug,折騰我一下午,痛苦。

原因:參數不匹配

解決方法:https://www.cnblogs.com/zero666/p/12154708.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM