其他分享
首页 > 其他分享> > js 使用FormData实现多文件上传

js 使用FormData实现多文件上传

作者:互联网

html:

<input type="file" accept="image/*"  id="jobData" onchange="onc()" style="position:absolute;top:0;left:0;font-size:34px; opacity:0" multiple />
<span id="filename" style="vertical-align: middle">未上传文件</span>

<input type="submit" class="btn btn-primary float-end " onclick="addshowpagejs()" value="确认上传" />

js:

// 显示上传文件名称
    function onc(){
        var obj = document.getElementById("jobData");
        var names = "文件-    ";
        for(var i=0;i<obj.files.length;i++){
            names = names.concat( i+1,":",obj.files[i].name,"    ");

        }
        document.getElementById("filename").innerText = names;
    }



    // 上传
    function addshowpagejs(){
        var formData = new FormData();
        var files = $("#jobData");
        for (var i = 0; i < files[0].files.length; i++) {
            formData.append("file", files[0].files[i]);
        }


        $.ajax({
            url: '/showpage/addshowpage',
            type: 'post',
            data: formData,
            cache: false,
            contentType: false, // 不使用默认请求头类型 application/x-www-form-urlencoded; charset=UTF-8
            processData: false, // 不序列化
            success: function() {
                alert("ok");

            },
            error: function (){
                alert("服务器正忙,请稍后再试...")
            }
        });

    }

controller:

@Controller
@RequestMapping("/showpage")
public class ShowPageController {

    @RequestMapping(value = "/addshowpage" , method = RequestMethod.POST)
    @ResponseBody
    public void addShowpage(@RequestParam("file") List<MultipartFile> uploadfile, HttpServletRequest request) {

        if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
            //循环输出上传文件
            for (MultipartFile file : uploadfile) {
                //获取上传文件原始名
                String originalFilename = file.getOriginalFilename();
                System.out.println(originalFilename);
                //设置上传文件的保存地址目录
                String dirPath = request.getServletContext().getRealPath("/files/showpage/");
                File filePath = new File(dirPath);
                System.out.println(dirPath);
                //如果保存文件的地址不存在,就先新建目录
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                //使用uuid重新命名上传的文件名称
                String newFilename = UUID.randomUUID() + "_" + originalFilename;
                System.out.println(newFilename);
                try {

                    //使用MultipartFile接口的方法完成文件的上传到指定位置
                    file.transferTo(new File(dirPath, newFilename));

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }else{
            System.out.println("失败");
        }
    }
}

标签:files,文件,uploadfile,FormData,js,file,var,上传
来源: https://blog.csdn.net/qq_45481620/article/details/121341802