当前位置 主页 > 网站技术 > 代码类 >

    spring boot搭建文件服务器解决同时上传多个图片和下载的问题

    栏目:代码类 时间:2019-11-24 18:08

    在平时的业务场景中,避免不了,要搭建文件上传服务器,作为公共服务。一般情况,只做了单个文件的上传,实际业务场景中,却发现单个文件上传,并不能满足一些业务需求,因此我们需要解决如何写一个同时上传多个文件的接口,并返回可下载的文件地址;

    废话不多讲,不再从头建立一个 Spring boot 项目,如果不知道的话,请直接前往官网查看实例。

    下面我们以上传图片为例,示例相对简单,仅供参考:

    1 后端上传图片接口逻辑

    UploadController.java
    package com.zz.controllers.fileUpload;
    import com.zz.Application;
    import com.zz.model.Response;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.web.server.LocalServerPort;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import java.io.*;
    import java.net.Inet4Address;
    import java.net.InetAddress;
    import java.nio.file.Path;
    import java.util.ArrayList;
    import java.util.UUID;
    import static com.zz.config.ConfigConstants.getFileDir;
    @RestController
    @Configuration
    public class UploadController {
     private static final Logger log = LoggerFactory.getLogger(Application.class);
     @Value("${server.port}")
     private String port;
     //获取当前IP地址
     public String getIp() {
      InetAddress localhost = null;
      try {
       localhost = Inet4Address.getLocalHost();
      } catch (Exception e) {
       log.error(e.getMessage());
       e.printStackTrace();
      }
      return localhost.getHostAddress();
     }
     @PostMapping(value = "/upload", consumes = {"multipart/form-data"})
     public Response upload(@RequestParam("file") MultipartFile[] files, Response response) {
      log.info("上传多个文件");
      StringBuilder builder = new StringBuilder();
      // file address
      String fileAddress ="http://"+ getIp()+ ":" + port + File.separator;
      ArrayList<String> imgUrls = new ArrayList<String>();
      try {
       for (int i = 0; i < files.length; i++) {
        // old file name
        String fileName = files[i].getOriginalFilename();
        // new filename
        String generateFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf("."));
        // store filename
        String distFileAddress = fileAddress + generateFileName;
        builder.append(distFileAddress+",");
        imgUrls.add(distFileAddress);
        // generate file to disk
        files[i].transferTo(new File(getFileDir() + generateFileName));
       }
      } catch (Exception e) {
       e.printStackTrace();
      }
      response.setMsg("success");
      log.info(builder.toString());
      response.setData(imgUrls);
      return response;
     }
    }
    
    

    相对于单个文件的接收,我们这里直接接受多个 file 对象,然后遍历生成每个对应的地址。

    其中:

    getFileDir 设置存放图片的地址,我选择存在项目外的其他地方

    com.zz.config.ConfigConstants.getFileDir
    package com.zz.config;
    public class ConfigConstants {
     public static String fileDir;
     public static String getFileDir() {
      fileDir = "/Users/wz/projects/blog/uploadFile/";
      return fileDir;
     }
    }