• Ajax异步上传多个文件并返回文件路径


    前端JSP页面代码

    <label>附件:</label>
    <form id="fileForm">
    <input type="file" name="files" multiple="multiple" >
    <input type="button" id="btn_add_file" value="上传附件" onclick="upload_files()">
    </form>
    <script>
    function upload_files(){
    var formData = new FormData($("#fileForm")[0]);
    $.ajax({
    url : path.basePath+"file/uploadFiles2.do",
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success : function(data) {
    alert("成功了!"+data);
    },
    error : function(data) {
    alert("失败了!"+data);
    }
    });
    </script>

    java springMVC后台代码

    @RequestMapping(value = "uploadFiles2.do", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFiles2(@RequestParam(value="files")List<MultipartFile> list,HttpServletRequest request) {
    System.out.println("**************************进入uploadFiles2方法*********************************");
    Map<String,String> map = new HashMap<String,String>();
    try {
    for (MultipartFile file : list) {
    String fileName = file.getOriginalFilename();
    String saveName = UUID.randomUUID().toString().replace("-","") + fileName.substring(fileName.lastIndexOf("."));
    String savedPath = request.getSession().getServletContext().getRealPath("/uploadFiles/");//获取服务器指定文件存取路径
    File saveDir = new File(savedPath);
    if (!saveDir.exists()){
    saveDir.mkdirs();
    }
    File saveFile = new File(savedPath, saveName);
    System.out.println(saveFile);
    map.put(fileName,saveFile.toString());
    file.transferTo(saveFile);
    }
    return map.toString();
    } catch (IllegalStateException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return null;
    }
  • 相关阅读:
    CSS 层叠样式表
    一. 图论
    二. log4j配置文件
    三.注解
    3. Map与Tuple
    MappedByteBuffer读写文件
    2. scala中的数组
    1.scala语法
    二. 模式匹配
    一.算法的数学基础
  • 原文地址:https://www.cnblogs.com/wanghongyun/p/9324434.html
Copyright © 2020-2023  润新知