栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 使用表单或者vue实现文件上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 使用表单或者vue实现文件上传

@TOC

本文的前端是HTML表单,另一种vue + axios,后端使用SpringBoot 2.x

一、创建项目

新建SpringBoot项目,同时导入依赖
项目结构

两个方法用的同一个控制层接口就直接先上控制层代码

二、控制层代码
package com.king.other.controller;

import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/file")
@Api(value = "文件上传接口", tags = "测试接口2")
public class FileController {

    //默认上传到的路径
    private final String filePath = "F:\A\";

    @PostMapping("/upload")
    @ApiOperation(value = "上传单个文件", tags = "测试接口2")
    public String upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest req) {
        if (!uploadFile.isEmpty()) {
            return saveFile(uploadFile);
        }
        return "上传失败!";
    }

    @PostMapping("/uploads")
    @ApiOperation(value = "上传多个文件", tags = "测试接口2")
    public String upload(@RequestParam("files") MultipartFile[] uploadFiles, HttpServletRequest req) {
        if (uploadFiles.length > 0) {
            return saveFile(uploadFiles);
        }
        return "上传失败!";
    }

    
    public String saveFile(MultipartFile... multipartFiles) {
        StringBuilder sb = new StringBuilder();
        try {
            for (MultipartFile multipartFile : multipartFiles) {
                multipartFile.transferTo(new File(filePath, multipartFile.getOriginalFilename()));

                sb.append(filePath).append(multipartFile.getOriginalFilename()).append("n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败!";
        }
        return sb.toString();
    }

}

三、表单实现文件上传 实现单文件上传

页面

实现多文件上传

页面

效果截图

四、使用vue + axios 实现文件上传 引入js文件


对应js


实现单文件上传

页面

 
实现多文件上传

页面

 
效果图


最后附带源码地址

Github
Gitee

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/726989.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号