springmvc+ajax实现多文件上传

这里使用了springboot项目

html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.js" ></script>
</head>
<body>
<h1>你好,世界!</h1>
<form id="from1" enctype="multipart/form-data">
    <input type="file" name="file" id="upfile" multiple="multiple" value="选择文件">
    <input  type="button" value="提交" id="btn"/>
</form>
</body>
<script >
    $("#btn").click(function(){
        var formData = new FormData($("#from1")[0]);/*传多个文件 $("#from1")[0]*/
        //var formData = new FormData();
        //formData.append("file",$("#upfile")[0].files[0]); /*传单个文件 */
        $.ajax({
            url: "/upload",
            type: "POST",
            data: formData,
            /**
             *必须false才会自动加上正确的Content-Type
             */
            contentType: false,
            /**
             * 必须false才会避开jQuery对 formdata 的默认处理
             * XMLHttpRequest会对 formdata 进行正确的处理
             */
            processData: false,
            success: function (data) {
                alert("上传成功!"+data);
               //console.log(data);
            },
            error: function () {
                alert("上传失败!");
            }
        });
    });
</script>
</html>

后台controller

package com.example.demo.action;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Controller
public class IndexAction {
    @RequestMapping("/index")
    public String index(ModelAndView model){
        //model.setViewName("index");
        return "index";
    }
    //返回json格式的数据
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile[] files){
        MultipartFile file=null;
        for(int i=0;i<files.length;i++){
            file=files[i];
            System.out.println(file.getOriginalFilename());
        }
        Map map  = new HashMap<>();
        map.put("return","success");
        String json = JSON.toJSONString(map);
        return json;
    }
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值