本文实例为大家分享了jQuery实现异步上传一个或多个文件的具体代码,供大家参考,具体内容如下
首先使用SpringMvc文件上传,需要引入第三方上传文件的jar:
commons-fileupload commons-fileupload 1.3.1 commons-io commons-io 2.4
响应json需要导入的包:
com.fasterxml.jackson.core jackson-databind 2.9.0 com.fasterxml.jackson.core jackson-core 2.9.0 com.fasterxml.jackson.core jackson-annotations 2.9.0
接下来看jsp文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>首页 同步上传一个文件
异步上传一个文件
异步上传一个文件,且表单有其他数据
异步上传多个文件,且表单有其他数据
下面是controller:
@Controller @RequestMapping("/upload") public class FileController { /** * 同步文件一个上传和异步上传一个文件,共同使用这一个控制器方法 * @param request * @param upload * @return * @throws IOException */ @RequestMapping(value = "/testUpload",method = RequestMethod.POST) public String upload(HttpServletRequest request, MultipartFile upload) throws IOException { //获取文件的保存路径 String path = request.getServletContext().getRealPath("/uploads"); //获取上传文件的名称 String filename = upload.getOriginalFilename(); //获取随机字符串 String prefix = UUID.randomUUID().toString().replaceAll("-", ""); filename = prefix + "_" + filename; //创建文件对象 File file = new File(path); //判断路径是否存在,不存在则创建 if(!file.exists()){ file.mkdir(); } //上传文件 upload.transferTo(new File(file,filename)); return "success"; } /** * 异步文件上传和表单数据 * @param request * @param upload * @return * @throws IOException */ @RequestMapping(value = "/testUpload2",method = RequestMethod.POST) public @ResponseBody Account upload2(HttpServletRequest request, MultipartFile upload, Account account) throws IOException { //获取文件的保存路径 String path = request.getServletContext().getRealPath("/uploads"); //获取上传文件的名称 String filename = upload.getOriginalFilename(); //获取随机字符串 String prefix = UUID.randomUUID().toString().replaceAll("-", ""); filename = prefix + "_" + filename; //创建文件对象 File file = new File(path); //判断路径是否存在,不存在则创建 if(!file.exists()){ file.mkdir(); } //上传文件 upload.transferTo(new File(file,filename)); return account; } /** * 异步多个文件上传和表单数据 * @param request * @param upload 采用数组接收 * @return * @throws IOException */ @RequestMapping(value = "/testUpload3",method = RequestMethod.POST) public @ResponseBody Account upload3(HttpServletRequest request, MultipartFile[] upload, Account account) throws IOException { //获取文件的保存路径 String path = request.getServletContext().getRealPath("/uploads"); //创建文件对象 File file = new File(path); //判断路径是否存在,不存在则创建 if(!file.exists()){ file.mkdir(); } for (MultipartFile multipartFile : upload) { //获取上传文件的名称 String filename = multipartFile.getOriginalFilename(); //获取随机字符串 String prefix = UUID.randomUUID().toString().replaceAll("-", ""); filename = prefix + "_" + filename; //上传文件 multipartFile.transferTo(new File(file,filename)); } return account; } }
public class Account implements Serializable { private int id; private String name; private float money; //getter or setter.... }
注意事项:
上传文件时,表单的 enctype 修改为:multipart/form-data;
后端使用 MultipartFile upload 对象接收,upload 必须和 的name属性一致;
上传多个文件,给 添加:multiple=“multiple”
效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。