• 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) {
           //操作
      }
    }
  • 相关阅读:
    java.lang.IllegalStateException: Failed to load ApplicationContext
    exit 和 return
    ORA-01031:insufficient privileges
    Errors running buider 'DeploymentBuilder' on project 'HFMS'
    unpack
    :Spring MVC +MyBatis +MySQL 登录查询Demo
    :Spring MVC +MyBatis +MySQL 登录查询Demo
    kill 某个进程
    10053 诊断事件
    11g 搜集直方图导致不走索引
  • 原文地址:https://www.cnblogs.com/jinghun/p/10399076.html
Copyright © 2020-2023  润新知