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) {
           //操作
      }
    }
  • 相关阅读:
    阅读笔记09
    阅读笔记08
    阅读笔记07
    阅读笔记06
    阅读笔记05
    有关eclipse连接SQL Server 2008的问题
    每周进度条05
    软件需求模式阅读笔记04
    每周进度条04
    软件需求模式阅读笔记03
  • 原文地址:https://www.cnblogs.com/jinghun/p/10399076.html
Copyright © 2011-2022 走看看