通过Ajax批量上传图片(springboot)

本文介绍如何在SpringBoot应用中结合Ajax技术,实现在前端批量上传图片的功能,包括HTML表单的创建,Controller层的处理方法以及相关的配置文件设置。

HTML

<form >
        <input type="file" webkitdirectory name="upimgs" id="upimgs" value="选择人脸库"/>           <br>
        <input type="button" value="上传" onclick="uppic()">
</form>



<script>
    var length;
    $("#upimgs").change(function () {
        length = this.files.length;
        console.log(length);
    })

    function uppic(){
        var formData = new FormData();
        var arr=new Array();
        var container;
        var i=0;
        for(let i=0;i<length;i++){
            formData.append('upimgs', $('#upimgs')[0].files[i]);
            console.log(formData.get("upimgs"));
        }
        container=formData.getAll("upimgs");
        for (var item in container) {
            arr[i] = container[item];
            i++;
        }
        console.log(arr);
        alert(formData);
        $.ajax({
            url: '/registpic/upstandardimg',
            type: 'POST',
            dataType:"json",
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            success:function(res) {
                alert(res.uppicmsg);
            },
            error:function (){
                alert("失败")
            }

        });
    }

</script>

Controller层

@RequestMapping("/upstandardimg")
    @ResponseBody
    public Object uploadfile(@RequestParam("upimgs") MultipartFile[] upimgs, HttpServletRequest request) throws IOException {
        Map<String, Object> map = new HashMap();
        map.put("uppicmsg", "上传成功");
        String filenames = null;
        for(MultipartFile multipartFile:upimgs){
            if(multipartFile.isEmpty()){
                System.out.println("空");
            }else {
                // 获取文件名
                String fileName = multipartFile.getOriginalFilename();
                System.out.println("上传文件原始的名字: " + fileName);

                // 使用uuid生成新文件名
                String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf("."), fileName.length());
                System.out.println("保存的文件的新名字: " + newFileName);

                // 获取年月日的日期格式
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String format = simpleDateFormat.format(new Date());

                // 生成以日期分割的文件路径
                File readPath = new File(UPLOAD_PATH_PREFIX + uploadPath + File.separator + format);
                System.out.println("存放的文件夹: " + readPath);
                System.out.println("存放文件的绝对路径: " + readPath.getAbsolutePath());
                // 判断文件夹是否存在
                if (!readPath.isDirectory()) {
                    // 创建文件夹
                    readPath.mkdirs();
                }

                // 文件真实的保存路径
                File file = new File(readPath.getAbsolutePath() + File.separator + newFileName);
                try {
                    multipartFile.transferTo(file);

                    // 获取存储路径
                    //String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + uploadPath + "/" + format + "/" + newFileName;
                } catch (IOException e) {
                    e.printStackTrace();
                    filenames = filenames + ", " + fileName;
                }


            }
        }
        if(filenames != null){
            map.put("uppicmsg", filenames+" " + "上传失败");
        }
        return map;
    }

配置文件

# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
#spring.servlet.multipart.max-request-size=10KB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=10MB
#spring.servlet.multipart.max-file-size=10KB

# 文件上传路径(相对于项目)
img.uploadPath=/standardpic

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值