在spring boot上进行ajax上传文件

本文介绍了如何在Spring Boot应用中实现Ajax无表单文件上传。前端使用div嵌套input方式,js设置enctype确保multipart/form-data类型,避免后台报错。同时,后端接口配置了文件上传大小限制,例如在application.properties中设定为100MB。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**

前端页面

**
由于我想试一下不使用表单来上传文件与文件名,在这里使用div嵌套input来使用

<div class="addDocument">
        <div class="DocumentTitle">
            <input name="title" type="text" class="form-control" placeholder="文件名" aria-describedby="basic-addon1" />
        </div>
        <div class="DocumentFile">
            <input name="file" type="file" accept=".xls,.dock,.doc,.pptx,.pdf" />
        </div>
        <div><button type="button" class="btn btn-primary" onclick="addFile()">提交按钮</button></div>
    </div>

在这里插入图片描述

js

enctype: ‘multipart/form-data’,如果这一行不加上去后台会报错误
Current request is not a multipart request

function addFile() {
        var formData = new FormData();
        formData.append("file", $("input[name='file']")[0].files[0]);
        formData.append("title",$("input[name='title']").val());
        $.ajax({
            type: "POST",           //因为是传输文件,所以必须是post
            url: 'document/addDocument',         //对应的后台处理类的地址
            data: formData,
            processData: false,
            contentType: false,
            enctype: 'multipart/form-data', //必须有
            dataType:"json",
            success: function (data) {
                alert(result.msg);
                if(result.type==1){
                    window.location.assign(result.url);
                }else{
                    location.reload();
                }
            }
        });
    }

后台接口

@RequestMapping("/addDocument")
    public String addDocument(@RequestParam("file") MultipartFile file,@RequestParam("title") String title){
        Subject subject = SecurityUtils.getSubject();
        String name = subject.getPrincipals().toString();
        Wrapper wrapper = new EntityWrapper<User>();
        wrapper.eq("name", name);
        User user = (User) userService.selectOne(wrapper);
        File foler=new File("src\\main\\resources\\document\\"+name);
        JSONObject json = new JSONObject();
        if (file.isEmpty()|| (int)file.getSize()==0) {
            json.put("type",2);
            json.put("msg","上传失败,请选择文件");
            String jsonString = json.toString();
            return jsonString;
        }
        if(!foler.exists()){//如果文件夹不存在
            foler.mkdirs();//创建文件夹
        }
        String filePath = "src\\main\\resources\\document\\"+name;
        String fileName = file.getOriginalFilename();
//        System.out.println(fileName);
//        System.out.println(title);
        String Tail = fileName.substring(fileName.lastIndexOf("."));
        File dest = new File( new File("src\\main\\resources\\document\\"+name).getAbsolutePath()+"\\" + title+Tail);
        try {
            file.transferTo(dest);
            Document document = new Document();
            document.setSize(String.valueOf(file.getSize()));
            document.setTitle(title);
            if(Tail.equals(".doc")||Tail.equals(".dock")) {
                document.setCid(3);
            }else if(Tail.equals(".ppt")||Tail.equals(".pptx")) {
                document.setCid(2);
            }else {
                document.setCid(1);
            }
            document.setAddress(filePath +"\\"+ title+Tail);
            document.setUid(user.getId());
            Date now = new Date();
            document.setCreateDate(now);
            documentService.insert(document);
            json.put("type",1);
            json.put("msg","上传成功");
            json.put("url","/index");
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            json.put("type",2);
            json.put("msg","上传失败");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            json.put("type",2);
            json.put("msg","上传失败");
        }
        String jsonString = json.toString();
        return jsonString;
    }

对于文件上传大小可以在application.properties中进行设置,我在这里设置为100MB

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值