zoukankan      html  css  js  c++  java
  • SpringMVC,SpringBoot利用ajax上传文件到后台

    1、传递单文件

    首先html文件中有个<input type=”file” name=”file” id=”file”/>元素。

    前台js写法:

    var formData=new FormData();
    formData.append("file",$("#file")[0].files[0]);
    formData.append("type",type);//也可以传递其他字段
    $.ajax({
        type:"post",
        url:" testController/uploadFile",
        data:formData,
        contentType: false,
        processData: false,
        dataType:"json",
        success:function(res){
        },
        error:function (msg) {
        }
    })

    后台接收方法:

    @RestController
    @RequestMapping("testController")
    public class testController {
    
      @RequestMapping("/uploadFile") 
      public String uploadFile (MultipartFile file,String type) {
           //操作
      }
    }

    2、传递多文件

    html文件中需要有个form表单:

    <form id="form" enctype="multipart/form-data">
        <input type="file" multiple="multiple" name="files">
    </form>

    前台js写法:

    var formData=new FormData($("#form")[0]); 
    formData.append("type",type);//也可以添加其他字段
    $.ajax({
        type:"post",
        url:" testController/uploadFiles",
        data:formData,
        contentType: false,
        processData: false,
        dataType:"json",
        success:function(res){
        },
        error:function (msg) {
        }
    })

    后台接收方法:

    @RestController
    @RequestMapping("testController")
    public class testController {
    
      @RequestMapping("/uploadFiles") 
      public String uploadFile (MultipartFile[] files,String type) {
           //操作
      }
    }
  • 相关阅读:
    Python 解决: from pip import main ImportError: cannot import name 'main'
    tensorflow学习笔记
    python多线程、多进程相关知识
    灰度发布相关
    自定义flume的hbase sink 的序列化程序
    pyspark数据准备
    利用pipeline批量插入数据到redis
    CentOS Linux系统下更改Apache默认网站目录
    更改nginx网站根目录
    chkconfig用法
  • 原文地址:https://www.cnblogs.com/jinghun/p/10399076.html
Copyright © 2011-2022 走看看