springBoot 中使用ajax上传文件到服务器

html页面,点击input来选择文件

<input type="file" class="form-control" id="file" name="file">
<button class="btn btn-default" onclick="sendFile()" type="button">发送文件</button>

js代码

function sendFile(){
    fileBox = $('#file')[0].files[0];
    if (fileBox === null){
        alert("请选择需要上传的文件");
        return false;
    }else {
        var formData = new FormData();
        formData.append("file",fileBox);
        //可以附带一些其他信息
        formData.append("userName",userName);
        $.ajax({
            type : "post",
            url : "/meeting/upload",
            data : formData,
            processData : false,
            contentType : false,
            success : function(data){
                if (data.end=="error") {
                    alert("文件提交失败!");
                }else{
                    alert("文件上传成功!");
                }}
        });
    }
}

后端controller代码

@PostMapping("/upload")
//MultipartFile 为springmvc用于接收文件的类
    public Map<String,String> upload(MultipartFile file, HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        String userName = request.getParameter("userName");
        if (file.getSize()>0){
            try {
            //System.getProperty("user.dir")可以获得该项目的根目录
                String path = System.getProperty("user.dir")+"/src/main/resources/uploadFile/";
                String name  = roomId+"_"+userName+"_"+file.getOriginalFilename();
                File file1 = new File(path,name);
                file.transferTo(file1);
                map.put("end","succeed");
            }catch (Error | IOException error){
                map.put("end","error");
            }
        }else {
            map.put("end","error");
        }
        return map;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值