MDN https://developer.mozilla.org/en-US/docs/Web/API/FormData
示例 无参构造 1 var formData = new FormData ();
有参构造 1 2 let myForm = document .getElementById ('myForm' );let formData = new FormData (myForm);
Methods 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 formData.append (name, value); formData.append (name, value, filename); formData.append ('username' , 'Chris' ); formData.append ('userpic' , myFileInput.files [0 ], 'chris.jpg' ); formData.append ('name' , true ); formData.append ('name' , 74 ); formData.append ('name' , 'John' ); formData.getAll ('name' ); var content = '<a id="a"><b id="b">hey!</b></a>' ; var blob = new Blob ([content], { type : "text/xml" });formData.append ("webmasterfile" , blob);
append() - 添加一个键 / 值对
delete() - 删除一个键 / 值对
set() - 修改或新增一个键 / 值对
get() - 返回指定的键关联的第一个值
getAll() - 返回指定 key 的所有值
has() - 返回一个布尔值,是否含有某个 key 值
entries() - 返回一个 iterator 对象,此对象可以遍历访问 FormData 中的键值对
keys() - 返回一个 iterator 对象,此对象可以遍历访问 FormData 中的所有 key,这些 key 是 USVString 对象
values() - 返回一个 iterator 对象,此对象可以遍历访问 FormData 中的所有 value
注意
console.log 无法打印出 formdata 对象,可以遍历对象打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>formdata + ajax 数据+文件上传</title> <script src="http://www.jq22.com/jquery/jquery-2.1.1.js"></script> </head> <body> <input type="file" name="files" multiple id="fileUpload" accept="image/*"> <script> //选择图片,并上传 $("#fileUpload").change(function () { var files = $("#fileUpload")[0].files; upload(files, function (result){ //返回结果 console.log(result); }); }); //上传图片 function upload(files, func) { var formdata = new FormData(); formdata.append("project", "scm"); formdata.append("module", "event"); formdata.append("changename", "1"); for (var i = 0, len = files.length; i < len; i++) { formdata.append("files", files[i]); } $.ajax({ url: 'http://192.168.0.81:8000/FileServer/uploadFiles', type: 'POST', data: formdata, async: false, cache: false, contentType: false, processData: false, success: function (result) { func(result); }, error: function (result) { func(result); } }); } </script> </body> </html>
后台示例 SpringMVC 1 2 3 4 5 6 7 8 9 10 11 @RequestMapping(value = "postFormData", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody public void postFormData (FilesuploadReq entity, HttpServletRequest request) { System.out.println(entity.toString()); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; List<MultipartFile> files = multipartRequest.getFiles("files" ); for (MultipartFile file : files) { System.out.println(file.getOriginalFilename()); } }
1 2 3 4 5 6 7 8 9 @Data public class FilesuploadReq { private String project; private String module ; private String changename; private MultipartFile[] files; }
SprintBoot 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 package com.bjtcrj.files.controller;import com.bjtcrj.files.bean.FilesuploadReq;import com.bjtcrj.files.bean.ResponseBean;import com.bjtcrj.files.util.FileGenerator;import lombok.extern.slf4j.Slf4j;import org.apache.commons.io.FileUtils;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.multipart.MultipartResolver;import org.springframework.web.multipart.support.StandardServletMultipartResolver;import javax.servlet.http.HttpServletRequest;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.Collection;import java.util.List;import java.util.Map;@RestController @Slf4j public class UploadFilesController { @GetMapping("/hello") public String hello () { return "hello 当前时间戳:" + System.currentTimeMillis(); } @PostMapping("/uploadFiles") @ResponseBody public ResponseBean uploadFiles (FilesuploadReq entity) { ResponseBean resultRes = new ResponseBean (); int code = ResponseBean.CODE_SUCCESS; String msg = "上传成功" ; if (StringUtils.isEmpty(entity.getModule())) { msg = "module 参数不能为空" ; code = ResponseBean.CODE_FAILED; resultRes.setCode(code); resultRes.setMsg(msg); return resultRes; } MultipartFile[] files = entity.getFiles(); List<String> imgs = new ArrayList <>(); File dest = null ; try { for (int i = 0 ; i < files.length; i++) { String fileName = files[i].getOriginalFilename(); String tempFilePath = FileGenerator.getFilePath(entity, fileName); dest = new File (FileGenerator.ROOTPATH + tempFilePath); files[i].transferTo(dest); imgs.add(tempFilePath); } } catch (IOException e) { code = ResponseBean.CODE_FAILED; msg = "上传失败:" + e.getMessage(); if (dest != null ) { try { FileUtils.forceDelete(dest); } catch (IOException ee) { ee.printStackTrace(); log.error("FileUtils.forceDelete 失败" ); } } e.printStackTrace(); } finally { resultRes.setCode(code); resultRes.setMsg(msg); String join = String.join("," , imgs); log.info(msg + ":" + join); resultRes.setData(join); } return resultRes; } @PostMapping("/uploadFiles_App") @ResponseBody public ResponseBean uploadFiles_App (FilesuploadReq entity, HttpServletRequest request) { ResponseBean resultRes = new ResponseBean (); int code = ResponseBean.CODE_SUCCESS; String msg = "上传成功" ; if (StringUtils.isEmpty(entity.getModule())) { msg = "module 参数不能为空" ; code = ResponseBean.CODE_FAILED; resultRes.setCode(code); resultRes.setMsg(msg); return resultRes; } MultipartResolver resolver = new StandardServletMultipartResolver (); MultipartHttpServletRequest mRequest = resolver.resolveMultipart(request); Map<String, MultipartFile> fileMap = mRequest.getFileMap(); List<String> imgs = new ArrayList <>(); Collection<MultipartFile> files = fileMap.values(); File dest = null ; try { for (MultipartFile file : files) { String fileName = file.getOriginalFilename(); String tempFilePath = FileGenerator.getFilePath(entity, fileName); String filepathname = FileGenerator.ROOTPATH + tempFilePath; dest = new File (filepathname); file.transferTo(dest); imgs.add(tempFilePath); } } catch (IOException e) { code = ResponseBean.CODE_FAILED; msg = "上传失败:" + e.getMessage(); if (dest != null ) { try { FileUtils.forceDelete(dest); } catch (IOException ee) { ee.printStackTrace(); log.error("FileUtils.forceDelete 失败" ); } } e.printStackTrace(); } finally { resultRes.setCode(code); resultRes.setMsg(msg); String join = String.join("," , imgs); log.info(msg + ":" + join); resultRes.setData(join); } return resultRes; } @DeleteMapping("/delete") public ResponseBean delete (HttpServletRequest request) { ResponseBean resultRes = new ResponseBean (); String paths = request.getParameter("paths" ); if (paths != null && !"" .equals(paths)) { String[] pathArr = paths.split("," ); for (String path : pathArr) { File file = new File (FileGenerator.ROOTPATH + path); try { FileUtils.forceDelete(file); } catch (IOException e) { e.printStackTrace(); } } } resultRes.setCode(ResponseBean.CODE_SUCCESS); resultRes.setMsg("删除成功" ); return resultRes; } } @Data public class FilesuploadReq { private String project; private String module ; private String changename; private MultipartFile[] files; }