小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot 上传文件示例

行业知识

SpringBoot 上传文件示例

2026-10-26 03:37:34 来源:互联网转载

示例效果:

前端代码:

上传文件示例

方式一:普通表单上传

方式二:fetch异步上传

const fileInput = document.getElementById('fileInput'); // 当文件被选中时上传文件 fileInput.addEventListener('change', function (e) { const file = e.target.files[0]; const formData = new FormData(); formData.append('file', file); fetch('/admin/upload', { method: 'POST', body: formData }).then(response => response.json()) // 如果API返回JSON,解析它 .then(data => { document.getElementById('fileInput').value = ""; alert(JSON.stringify(data)); }) // 处理解析后的数据 .catch(error => console.error('Error:', error)); // 处理错误 });

方式三:文件和文本一起提交


function submitForm() { const text = document.getElementById('text').value; const file = document.getElementById('file').files[0]; const formData = new FormData(); formData.append('text', text); formData.append('file', file); fetch('/admin/upload', { method: 'POST', body: formData }).then(response => response.json()) .then(data => { alert(JSON.stringify(data)); }); }

后台代码

 @RequestMapping(value = "/upload", method = RequestMethod.POST)    @ResponseBody    public String upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "text", required = false) String text) {        //文件保存路径为在D盘下的upload文件夹,可以按照自己的习惯修改        String FILE_UPLOAD_PATH = "D:\upload\";        //如果目录不存在,则创建目录        Path path = Paths.get(FILE_UPLOAD_PATH);        if (!Files.exists(path)) {            try {                Files.createDirectories(path);            } catch (IOException e) {                e.printStackTrace();            }        }        if (file.isEmpty()) {            return "文件上传失败";        }        String fileName = file.getOriginalFilename();        String suffixName = fileName.substring(fileName.lastIndexOf("."));        //生成文件名称通用方法        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");        Random r = new Random();        StringBuilder tempName = new StringBuilder();        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);        String newFileName = tempName.toString();        try {            //保存文件            byte[] bytes = file.getBytes();            Path filePath = Paths.get(FILE_UPLOAD_PATH + newFileName);            Files.write(filePath, bytes);        } catch (IOException e) {            e.printStackTrace();        }        var res = new JSONObject();        res.put("flag", true);        res.put("body", "上传成功");        res.put("text", text);        return res.toString();    }

此处仅演示如何实现简单的文件上传,实际环境中,还需做相应的身份认证,权限控制等。

上一篇:网络检测仪主机1号灯不亮怎么办呀

下一篇:真的吗?都是吉首大学张院校友吗