Springboot 简单实现文件上传

本文介绍如何使用SpringBoot实现文件上传功能,通过前端JavaScript与后端Controller交互,完成文件选择、上传、保存及状态反馈。文章详细展示了前端的模态框触发、FormData构造及AJAX调用,以及后端文件接收、存储路径设置、文件名处理和响应结果返回的全过程。

Springboot 简单实现文件上传

一.js

$("button[name='uploadbtn']").click(function () {
                var hid = this.id;
                var uid = loginid;
                $('#uploadmodal').modal("show");
                $("button[name='uploadbtn2']").click(function () {
                    var formData = new FormData(document.getElementById("upload-form"));
                    $.ajax({
                        url: "homework/upload",
                        method: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (resp) {
                            if(resp.result!=null){
                                $.getJSON("homework/saveDetails/"+uid+"/"+hid+"/"+resp.result , function (json) {
                                    if ("outtime"==json.rs){
                                        alert("已超时");
                                    }else if("fail"==json.rs){
                                        alert("失败");
                                    }else{
                                        alert(" 添加成功");
                                        $('#modalhwdetail2').modal('hide');
                                    }
                                })

                            }else{
                                alert("上传失败");
                            }
                        }
                    });

                })
            })

二.Controller

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map upload(@RequestParam MultipartFile myFile, HttpSession session) throws IOException {
        String originalFilename = myFile.getOriginalFilename();
        int pos = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(pos);
        String realPath = "D:/tmp";
        String uuid = UUID.randomUUID().toString();
        String fullPath = realPath + File.separator + uuid + suffix;
        String homeworkid=File.separator + uuid + suffix;
        InputStream in = null;
        try {
            in = myFile.getInputStream();
            OutputStream out = new FileOutputStream(new File(fullPath));
            int len = 0;
            byte[] buf = new byte[3 * 1024];
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map= new HashMap();
        map.put("result",homeworkid);
        return map;
    }


    @RequestMapping("saveDetails/{uid}/{hid}/{result}")
    public Map saveDetails(@PathVariable("uid") String uid, @PathVariable("hid") String hid,@PathVariable("result") String homeworkid) {
        Map map = new HashMap();
        int rs = hs.savedetails(uid, hid,homeworkid);
        if (rs > 0) {
            map.put("rs", "success");
        } else if (rs == -1) {
            map.put("rs", "outtime");
        } else {
            map.put("rs", "fail");
        }
        return map;
    }

三.Service

public int savedetails(String uid, String hid,String homeworkid) {
        int rs = 0;
        List<Homework> list = hr.findAllById(hid);
        if (new Date(System.currentTimeMillis()).getTime() > list.get(0).getFinishTime().getTime()) {
            rs = -1;
        } else {
            if (dd.queryfindexist(uid, hid).size() > 0) {
                dd.queryuploadDTOListMap2(uid, hid, homeworkid,new Timestamp(new java.util.Date().getTime()));
                rs = 1;
            } else {
                dd.queryuploadDTOListMap(uid, hid, homeworkid,new Timestamp(new java.util.Date().getTime()));
                rs = 1;
            }
        }
        return rs;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值