java 实现文件夹上传(springBoot 框架)

Posted 云储储

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 实现文件夹上传(springBoot 框架)相关的知识,希望对你有一定的参考价值。

java 实现文件夹上传(springBoot 框架)

有时我们后台管理等服务可能会有这样一个简单需求,就是根据文件夹将整个文件夹下的所有资源都上传到我们的服务器上,本人也是搜索了大量资料,最终以最简单便捷的方式实现该功能,具体操作步骤如下

一、前端如何设置上传组件并将资源上传到后台服务

这里的项目框架为若依VUE版本,下面将核心的代码抽离出来进行代码示例,方便大家快速阅读

1)首先我们需要新建一个用来提交文件夹的form表单

1.添加一个 type=file 的 input 提交组件,添加 webkitdirectory 标识来使用文件夹上传功能
2.添加 @change=“uploadSoundCodeFolder” 事件,当我们上传了文件夹后将触发 uploadSoundCodeFolder() 函数来处理上传逻辑

<form id="uploadSoundCodeFolderForm" 
style="display: none" method="post" 
enctype="multipart/form-data">
  <input id="fileFolder" name="fileFolder" type="file" 
 		@change="uploadSoundCodeFolder" webkitdirectory>
</form>

uploadSoundCodeFolder() 实现逻辑如下

uploadSoundCodeFolder(e)
      this.uploadSoundCodeLoading = true;
      //获取到选中的文件夹内的所有文件
      //files 为一个集合
      //可通过遍历 files 的方式获取到每个文件的大小等数据,来实现大小限制等需求
      let files = e.target.files;
		
      //中间省略大小限制等需求......
      
      //获取表单数据
      let formData = new FormData(document.getElementById("uploadSoundCodeFolderForm"));

	  //调用后台服务方法来提交该表单数据
	  uploadSoundCode(formData).then((res)=>
                _this.$message.success("上传成功")
				//上传成功后清空表单数据
      			$("#fileFolder").val('');
      )

2)然后我们添加自己框架内的一些按钮来触发该隐藏的表单

这样做的好处是使用了form文件夹上传的功能,却不用使用他的UI

<!-- 首先创建一个按钮用来触发上传事件 uploadSoundCodeBtn() -->
<el-button  v-loading="uploadSoundCodeLoading" 
@click="uploadSoundCodeBtn">
上传文件夹
</el-button>
/*上传事件触发的方法*/
uploadSoundCodeBtn()
  $("#fileFolder").click();
,

二、后台如何接收处理文件夹表单数据

这里我们使用 List fileFolde 类型来接受前端发来的文件集合,fileFolde为表单里面的 name

@RequestMapping(value="/uploadSoundCode",method= RequestMethod.POST)
public AjaxResult uploadSoundCode(List<MultipartFile> fileFolde) throws IOException 
        String soundCodeUrl = HereUtil.uploadSoundCode(fileFolder);
        return AjaxResult.success(soundCodeUrl);
    

然后根据业务将文件保存到服务器就行了

public static String uploadSoundCode(List<MultipartFile> files) throws IOException 

        for (MultipartFile file : files) 
            String fileName = file.getOriginalFilename();
            if (StrUtil.isBlank(fileName))
                continue;
            
			
			//上传后的URL全路径
            String fullFilePath = "上传的跟路径" + fileName;
            FileUtil.writeFromStream(file.getInputStream(), fullFilePath);
        

        return "";
    

Java:SpringBoot使用EasyExcel实现Excel文件的导出下载和上传导入功能

SpringBoot使用EasyExcel实现Excel文件的导出下载和上传导入功能

文件目录

$ tree -I target
.
├── README.md
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── example
        │           └── demo
        │               ├── DemoApplication.java
        │               ├── controller
        │               │   └── EasyExcelController.java
        │               ├── converter
        │               │   └── GenderConverter.java
        │               └── excel
        │                   └── Member.java
        └── resources
            ├── application.properties
            └── json
                └── members.json

依赖 pom.xml


<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.11</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!--EasyExcel相关依赖-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.68</version>
    </dependency>

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-json</artifactId>
        <version>5.8.10</version>
    </dependency>

</dependencies>

Member.java

package com.example.demo.excel;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.example.demo.converter.GenderConverter;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.Date;

/**
 * 购物会员
 * Created by macro on 2021/10/12.
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class Member 
    @ExcelProperty("ID")
    @ColumnWidth(10)
    private Long id;

    @ExcelProperty("用户名")
    @ColumnWidth(20)
    private String username;

    @ExcelIgnore
    private String password;

    @ExcelProperty("昵称")
    @ColumnWidth(20)
    private String nickname;

    @ExcelProperty("出生日期")
    @ColumnWidth(20)
    @DateTimeFormat("yyyy-MM-dd")
    private Date birthday;

    @ExcelProperty("手机号")
    @ColumnWidth(20)
    private String phone;

    @ExcelIgnore
    private String icon;

    @ExcelProperty(value = "性别", converter = GenderConverter.class)
    @ColumnWidth(10)
    private Integer gender;

GenderConverter.java

package com.example.demo.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.StringUtils;

/**
 * excel性别转换器
 * Created by macro on 2021/12/29.
 */
public class GenderConverter implements Converter<Integer> 
    @Override
    public Class<?> supportJavaTypeKey() 
        //对象属性类型
        return Integer.class;
    

    @Override
    public CellDataTypeEnum supportExcelTypeKey() 
        //CellData属性类型
        return CellDataTypeEnum.STRING;
    

    @Override
    public Integer convertToJavaData(ReadConverterContext<?> context) throws Exception 
        //CellData转对象属性
        String cellStr = context.getReadCellData().getStringValue();

        if (StringUtils.isEmpty(cellStr)) return null;

        if ("男".equals(cellStr)) 
            return 0;
         else if ("女".equals(cellStr)) 
            return 1;
         else 
            return null;
        
    

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) throws Exception 
        //对象属性转CellData
        Integer cellValue = context.getValue();

        if (cellValue == null) 
            return new WriteCellData<>("");
        

        if (cellValue == 0) 
            return new WriteCellData<>("男");
         else if (cellValue == 1) 
            return new WriteCellData<>("女");
         else 
            return new WriteCellData<>("");
        
    

EasyExcelController.java

package com.example.demo.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.demo.excel.Member;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;
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.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

/**
 * EasyExcel导入导出测试Controller
 * Created by macro on 2021/10/12.
 */
@Controller
@RequestMapping("/easyExcel")
public class EasyExcelController 

    /**
     * 下载地址:http://localhost:8080/easyExcel/exportMemberList
     *
     * @param response
     */
    @SneakyThrows(IOException.class)
    @RequestMapping(value = "/exportMemberList", method = RequestMethod.GET)
    public void exportMemberList(HttpServletResponse response) 
        this.setExcelResponseHeader(response, "会员列表");

        // List<Member> memberList = LocalJsonUtil.getListFromJson("json/members.json", Member.class);

        // https://blog.csdn.net/qq6420529/article/details/125215520
        ClassPathResource classPathResource = new ClassPathResource("/json/members.json");

        JSONArray objects = JSONUtil.readJSONArray(classPathResource.getFile(), Charset.forName("utf-8"));
        List<Member> memberList = objects.toList(Member.class);

        EasyExcel.write(response.getOutputStream())
                .head(Member.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("会员列表")
                .doWrite(memberList);
    


    /**
     * 从Excel导入会员列表
     * <p>
     * http://localhost:8080/easyExcel/importMemberList
     *
     * @param file
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/importMemberList", method = RequestMethod.POST)
    @ResponseBody
    public List<Member> importMemberList(@RequestPart("file") MultipartFile file) 
        List<Member> memberList = EasyExcel.read(file.getInputStream())
                .head(Member.class)
                .sheet()
                .doReadSync();
        return memberList;
    


    /**
     * 设置excel下载响应头属性
     */
    private void setExcelResponseHeader(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException 
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
    

members.json

[
  
    "id": 1,
    "username": "刘备",
    "password": "123456",
    "nickname": "刘玄德",
    "birthday": "2000-10-10",
    "phone": "1234567890",
    "icon": "icon",
    "gender": "1"
  ,
  
    "id": 2,
    "username": "关于",
    "password": "234567",
    "nickname": "关云长",
    "birthday": "2000-10-10",
    "phone": "1234567890",
    "icon": "icon",
    "gender": "1"
  ,
  
    "id": 3,
    "username": "用户名",
    "password": "password",
    "nickname": "昵称",
    "birthday": "2000-10-10",
    "phone": "1234567890",
    "icon": "icon",
    "gender": "0"
  
]

下载的文件 会员列表.xlsx

上传文件

[
    
        "id": 1,
        "username": "刘备",
        "password": null,
        "nickname": "刘玄德",
        "birthday": "2000-10-09T16:00:00.000+00:00",
        "phone": "1234567890",
        "icon": null,
        "gender": 1
    ,
    
        "id": 2,
        "username": "关于",
        "password": null,
        "nickname": "关云长",
        "birthday": "2000-10-09T16:00:00.000+00:00",
        "phone": "1234567890",
        "icon": null,
        "gender": 1
    ,
    
        "id": 3,
        "username": "用户名",
        "password": null,
        "nickname": "昵称",
        "birthday": "2000-10-09T16:00:00.000+00:00",
        "phone": "1234567890",
        "icon": null,
        "gender": 0
    
]

以上是关于java 实现文件夹上传(springBoot 框架)的主要内容,如果未能解决你的问题,请参考以下文章

基于华为云obs实现文件上传下载(技术栈mysql+springboot+Maven+jsp+java)的技术分享

基于华为云obs实现文件上传下载(技术栈mysql+springboot+Maven+jsp+java)的技术分享

利用Java实现断点上传

SpringBoot实现文件上传下载

SpringBoot整合FastDFS实现文件的上传下载和删除

SpringBoot整合FastDFS实现文件的上传下载和删除