springboot文件上传,支持多文件上传

文件上传至指定目录,可在配置文件中修改指定路径,同时支持多文件同时上传

完整展示

在这里插入图片描述
var code = “e18819b2-e588-40fb-bb60-f042ecc6fce3”

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>FileUpload Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <link th:href="@{/css/bootstrap.min.css}" href="../static/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link th:href="@{/css/fileinput/fileinput.min.css}" href="../static/css/fileinput/fileinput.min.css"
          rel="stylesheet" type="text/css">
    <link th:href="@{/css/font-awesome.css}" href="../static/css/font-awesome.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2" style="margin-top: 7%">
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <input id="fileUpload" name="fileUpload" multiple="multiple" class="file" type="file" data-preview-file-type="text">
                        <div id="tip-warn" class="alert alert-warning fade in" style="margin-top: 10px;display: none">

                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
<script th:src="@{/js/jquery.min.js}" src="../static/js/jquery.min.js"></script>
<script th:src="@{/js/bootstrap.min.js}" src="../static/js/bootstrap.min.js"></script>
<script th:src="@{/js/plugins/fileinput/fileinput.min.js}" src="../static/js/plugins/fileinput/fileinput.min.js"></script>
<script>
    $("#fileUpload").fileinput({
        uploadUrl: "import", //上传的地址
        allowedFileExtensions: ['xls', 'xlsx', 'txt']//接收的文件后缀
    }).on('filepreupload', function (event, data) {     //上传中
        console.log(data);
    }).on("fileuploaded", function (event, data) {    //文件上传成功
        console.log('文件上传成功!' + data.id);
    }).on('fileerror', function (event, data) {  //文件上传失败
        console.log('文件上传失败!' + data.id);
    });
</script>
</html>
单文件和多文件的区别就是在  multiple="multiple“ 这里,后面也可以在fileinput的js中添加其他参数,具体看官方文档

后端代码

controller类
package comn.duplicall.upload.controller;

import comn.duplicall.upload.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author liangyafeng
 * @Description:
 * @date 2020/4/21 17:01
 */
@Controller
@Slf4j
public class UploadController {

    //配置文件中配置要上传文件保存的路径

    @Value("${filePath}")
    private String filePath;

    @RequestMapping(value = "File")
    public String toFile() {
        return "FileUpload";
    }


    @RequestMapping(value = "import", method = RequestMethod.POST)
    public ResponseEntity importFile(@RequestParam("fileUpload") MultipartFile[] fileUpload) {
        String[] str = new String[fileUpload.length];
        //服务器中文件不存在,就创建配置文件中的文件夹
        File[] files = new File(filePath).listFiles();
        if (files == null) {
            new File(filePath).mkdirs();
        }
        try {
            for (int i = 0; i < fileUpload.length; i++) {
                String fileName = fileUpload[i].getOriginalFilename();
                File file = new File(filePath, fileName);
                InputStream is = fileUpload[i].getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = is.read(bytes)) != -1) {
                    fos.write(bytes, 0, length);
                }
                is.close();
                fos.close();
                str[i] = file.getAbsolutePath();
                log.info("upload {} success",fileName);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(new Result(null, true), HttpStatus.OK);
    }

}

Result工具类
package comn.duplicall.upload.util;

/**
 * @author liangyafeng
 * @Description:
 * @date 2020/4/20 16:29
 */
public class Result<T> {
    //代码
    private int code;
    //提示信息
    private String message;
    //具体内容
    private T data;

    // 是否成功
    private boolean success;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public Result(T data, boolean success) {
        this.data = data;
        this.success = success;
    }

    public Result() {
    }
}

配置文件(application.yml)

设置上传的路径
filePath: c:/upload
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中实现带有多参数的文件上传可以通过以下步骤完成。 1. 在前端页面中添加一个文件上传表单,包含需要传递的其他参数。例如,可以使用HTML的表单元素和input标签来接收参数和文件。 ``` <form action="/upload" method="post" enctype="multipart/form-data"> <input type="text" name="param1" /> <input type="text" name="param2" /> <input type="file" name="file" /> <input type="submit" value="Submit" /> </form> ``` 2. 在Spring Boot的控制层中定义一个处理文件上传的接口。该接口中可以使用`@RequestParam`注解来获取其他参数,使用`@RequestParam("file")`注解来获取上传的文件。 ``` @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file, @RequestParam String param1, @RequestParam String param2) { // 处理文件上传和其他参数逻辑 // ... return "上传成功"; } ``` 3. 在接口实现中,可以使用`MultipartFile`对象获取上传的文件内容,使用普通的参数获取其他参数内容。根据业务需求,可以对上传的文件进行保存、处理等操作。 ``` if (!file.isEmpty()) { // 获取文件内容 byte[] fileBytes = file.getBytes(); // 保存文件到指定位置 Path filePath = Paths.get("上传文件目录", file.getOriginalFilename()); Files.write(filePath, fileBytes); // 处理其他参数 // ... } ``` 通过以上步骤,就可以实现在Spring Boot中上传带有多参数的文件。在控制层接口中,使用`@RequestParam`注解获取其他参数,使用`MultipartFile`对象获取上传的文件。然后根据业务需求进行文件操作和参数处理即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值