文件上传与下载(本地和远程)

  1. Controller
package com.ydtech.modules.admin.controller;

import com.ydtech.core.page.HttpResult;
import com.ydtech.modules.esm.service.UpdownLoadService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @Author: shixk
 * @create: 2021/9/3 15:28
 * description: 文件上传与下载
 */
@Api(tags = {"UpdownLoadController"},description = "文件上传与下载")
@Slf4j
@RestController
@RequestMapping("/updownLoad")
public class UpdownLoadController {

    @Autowired
    private UpdownLoadService updownLoadService;

    //多文件上传
    @ApiOperation(value = "上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "files", value = "MultipartFile文件"),
            @ApiImplicitParam(name = "path", value = "自定义路径")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "出现异常"),
            @ApiResponse(code = 200, message = "请求成功")
    })
    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public HttpResult upload(@RequestParam("files") MultipartFile[] files, @RequestParam(value = "path", required = false)String path) throws IOException {
        HttpResult result = null;
        try {
            result = updownLoadService.upload(files,path);
        } catch (Exception e) {
            result = HttpResult.error("上传文件失败!"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    //根据DIRID上传文件
    @ApiOperation(value = "根据DIRID上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "files", value = "MultipartFile文件"),
            @ApiImplicitParam(name = "dirid", value = "文件夹id")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "出现异常"),
            @ApiResponse(code = 200, message = "请求成功")
    })
    @RequestMapping(value = "/uploadFilesByDirId", method = RequestMethod.POST)
    public HttpResult uploadFilesByDirId(@RequestParam("files") MultipartFile[] files, @RequestParam(value = "dirid")String dirid) throws IOException {
        HttpResult result = null;
        try {
            result = updownLoadService.uploadFilesByDirId(files,dirid);
        } catch (Exception e) {
            result = HttpResult.error("上传文件失败!"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    

    //文件查询
    @ApiOperation(value = "文件夹查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dirid", value = "文件夹id")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "出现异常"),
            @ApiResponse(code = 200, message = "请求成功)")
    })
    @RequestMapping(value ="/select",method = RequestMethod.GET)
    public HttpResult select(@RequestParam("dirid")String dirid){
        HttpResult result = null;
        try {
            result = updownLoadService.select(dirid);
        } catch (Exception e) {
            result = HttpResult.error("文件查询失败!"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    //文件查询
    @ApiOperation(value = "文件查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileid", value = "文件id")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "出现异常"),
            @ApiResponse(code = 200, message = "请求成功)")
    })
    @RequestMapping(value ="/selectFileid",method = RequestMethod.GET)
    public HttpResult selectFileid(@RequestParam("fileid")String fileid){
        HttpResult result = null;
        try {
            result = updownLoadService.selectFileid(fileid);
        } catch (Exception e) {
            result = HttpResult.error("文件查询失败!"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    //文件下载
    @ApiOperation(value = "下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileid", value = "文件id")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "出现异常"),
            @ApiResponse(code = 200, message = "请求成功)")
    })
    @RequestMapping(value ="/download",method = RequestMethod.GET)
    public HttpResult download(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileid")String fileid){
        HttpResult result = null;
        try {
            result = updownLoadService.download(request,response,fileid);
        } catch (Exception e) {
            result = HttpResult.error("下载文件失败!"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    //文件删除
    @ApiOperation(value = "删除文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileid", value = "文件id")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "出现异常"),
            @ApiResponse(code = 200, message = "请求成功)")
    })
    @RequestMapping(value ="/deleteFile",method = RequestMethod.GET)
    public HttpResult deleteFile(@RequestParam("fileid")String fileid){
        HttpResult result = null;
        try {
            result = updownLoadService.deleteFile(fileid);
        } catch (Exception e) {
            result = HttpResult.error("删除文件失败!"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}

  1. UpdownLoadService
package com.ydtech.modules.esm.service;

import com.ydtech.core.page.HttpResult;
import com.ydtech.modules.ins.model.InsFileDto;
import com.jcraft.jsch.SftpException;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @Author: shixk
 * @create: 2021/9/3 15:43
 * description:
 */
public interface UpdownLoadService {

    /**
     * 对文件上传
     * @param files   文件files
     * @param dirId 文件夹Id ,可传空
     * @param path 指定路径
     * @return
     */
    HttpResult upload(MultipartFile[] files, String dirId, String path) throws IOException, SftpException;

    /**
     * 二进制对文件上传
     * @param bytes   二进制文件
     * @param fileName  文件名
     * @param dirId 文件夹Id ,可传空
     * @param path 指定路径
     * @return
     */
    InsFileDto upload(byte[] bytes, String fileName, String dirId, String path) throws IOException, SftpException;

    /**
     * 对文件上传
     * @param files   文件files
     * @param path 指定路径
     * @return
     */
    HttpResult upload(MultipartFile[] files, String path) throws IOException, SftpException;

    /**
     * 文件下载
     * @param request
     * @param response
     * @param fileId 文件ID
     * @return
     */
    HttpResult download(HttpServletRequest request, HttpServletResponse response, String fileId) throws IOException, SftpException;

    /**
     * 删除文件
     * @param fileId
     * @return
     */
    HttpResult deleteFile(String fileId) throws SftpException;

    /**
     * 文件查询
     * @param dirId
     * @return
     */
    HttpResult select(String dirId);

    /**
     * 文件查询
     * @param fileid
     * @return
     */
    HttpResult selectFileid(String fileid);


    /**
     * 根据DIRID上传文件
     * @param files
     * @param dirId
     * @return
     */
    HttpResult uploadFilesByDirId(MultipartFile[] files, String dirId) throws IOException, SftpException;


    /**
     * 将BASE64转为文件流上传
     * @param base64
     * @param dirId
     * @return
     */
    HttpResult uploadFilesByDirId(String base64, String dirId) throws IOException, SftpException;
}

  1. impl
package com.ydtech.modules.esm.service.impl;

import cn.hutool.core.codec.Base64;
import com.jcraft.jsch.SftpException;
import com.ydtech.aop.exception.DescribeException;
import com.ydtech.core.page.HttpResult;
import com.ydtech.modules.esm.dao.DualidMapper;
import com.ydtech.modules.esm.service.UpdownLoadService;
import com.ydtech.modules.ins.dao.InsFileMapper;
import com.ydtech.modules.ins.model.InsFileDto;
import com.ydtech.utils.SFTPUtil;
import com.ydtech.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: shixk
 * @create: 2021/9/3 15:49
 * description:
 */
@Slf4j
@Service
public class UpdownLoadServiceImpl implements UpdownLoadService {


    @Value("${upload.host}")
    private String upload_host;
    @Value("${upload.username}")
    private String upload_username;
    @Value("${upload.password}")
    private String upload_password;
    @Value("${upload.basepath}")
    private String upload_basepath;
    @Value("${upload.url}")
    private String upload_url;
    // 路径中的斜杠
    private static final String FILE_SEPARATOR = "/";

    @Autowired
    private DualidMapper dualidMapper;
    @Autowired
    private InsFileMapper insFileMapper;

    @Autowired
    private Environment environment;

    /**
     * 对文件上传
     *
     * @param files    文件files
     * @param dirId 文件夹id
     * @param path 指定路径
     * @return
     */
    @Override
    public HttpResult upload(MultipartFile[] files, String dirId, String path) throws IOException, SftpException {
        // 返回的文件信息
        List<InsFileDto> list = new ArrayList<>();
        String msg = "文件上传成功";
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        List<String> paths = generatePath(path, dirId);
        // 原文件名
        String fileOriName = null;
        //最终文件名:命名规则:当前时间搓+.+文件类型
        String finalfirstName = null;
        try {
            for (int i = 0; i < files.length; ++i) {
                file = files[i];
                //获取文件类型
                String filetype = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                //校验文件类型
                this.checkFileType(filetype);
                if (!file.isEmpty()) {
                    byte[] file_bytes = file.getBytes();
                    //原文件名
                    fileOriName = file.getOriginalFilename();
                    // 新文件名
                    finalfirstName = this.makeFileName(fileOriName);
                    //文件上传到服务器
                   /* SFTPUtil sftp = new SFTPUtil(upload_username, upload_password, upload_host, 22);
                    sftp.login();
                    ByteArrayInputStream bin = new ByteArrayInputStream(file_bytes);
                    sftp.upload(upload_basepath + paths.get(1), paths.get(0), finalfirstName, bin);
                    sftp.logout();*/
                    String filePath = upload_basepath + paths.get(1)+paths.get(0);
                    File file1 = new File(filePath);
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath+FILE_SEPARATOR  + new String(finalfirstName.getBytes("utf-8"), "utf-8"))));//设置文件路径及名字
                    stream.write(file_bytes);// 写入
                    stream.close();

                    // 生成文件id  F开头
                    InsFileDto dto = new InsFileDto();
                    dto.setDirid(paths.get(0));
                    dto.setFileid(dualidMapper.GetFileIdNext());
                    dto.setOldfilename(fileOriName);
                    dto.setNewfilename(finalfirstName);
                    dto.setFilepath(upload_basepath + paths.get(1) + paths.get(0));
                    dto.setUrl(upload_url + "upload" +FILE_SEPARATOR+ paths.get(1)+paths.get(0) + FILE_SEPARATOR + finalfirstName);
                    dto.setCtratetime(new Date());
                    dto.setUpdatetime(new Date());
                    list.add(dto);
                    insFileMapper.insert(dto);
                    // 存储表内
                } else {
                    msg = "上传文件为空!";
                    throw new DescribeException(msg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.info("上传文件结果:"+list);
        return HttpResult.ok(msg, list);
    }

    /**
     * 二进制对文件上传
     * @param bytes   二进制文件
     * @param fileName  文件名
     * @param dirId 文件夹Id ,可传空
     * @param path 指定路径
     * @return
     */
    @Override
    public InsFileDto upload(byte[] bytes, String fileName, String dirId, String path) throws IOException, SftpException {
        List<String> paths = generatePath(path, dirId);
        //最终文件名:命名规则:当前时间搓+.+文件类型
        String finalfirstName = null;
        BufferedOutputStream stream = null;
        try {
            //获取文件类型
            String filetype = fileName.substring(fileName.lastIndexOf(".") + 1);
            //校验文件类型
            this.checkFileType(filetype);

            // 新文件名
            finalfirstName = this.makeFileName(fileName);
           /* //文件上传到服务器
            SFTPUtil sftp = new SFTPUtil(upload_username, upload_password, upload_host, 22);
            sftp.login();
            ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
            sftp.upload(upload_basepath + paths.get(1), paths.get(0), finalfirstName, bin);
            sftp.logout();*/
            String filePath = upload_basepath + paths.get(1)+paths.get(0);
            File file1 = new File(filePath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            stream = new BufferedOutputStream(new FileOutputStream(
                    new File(filePath+FILE_SEPARATOR  + new String(finalfirstName.getBytes("utf-8"), "utf-8"))));//设置文件路径及名字
            stream.write(bytes);// 写入
            stream.close();

            // 生成文件id  F开头
            InsFileDto dto = new InsFileDto();
            dto.setDirid(paths.get(0));
            dto.setFileid(dualidMapper.GetFileIdNext());
            dto.setOldfilename(fileName);
            dto.setNewfilename(finalfirstName);
            dto.setFilepath(upload_basepath + paths.get(1) + paths.get(0));
            dto.setUrl(upload_url + "upload" +FILE_SEPARATOR+ paths.get(1)+paths.get(0) + FILE_SEPARATOR + finalfirstName);
            dto.setCtratetime(new Date());
            dto.setUpdatetime(new Date());
            insFileMapper.insert(dto);
            // 存储表内

            log.info("上传文件结果:"+dto);
            return dto;

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public HttpResult upload(MultipartFile[] files, String path) throws IOException, SftpException {
        return this.upload(files,null, path);
    }

    /**
     * 文件下载
     *
     * @param request
     * @param response
     * @param fileId 文件ID
     * @return
     */
    @Override
    public HttpResult download(HttpServletRequest request, HttpServletResponse response, String fileId) throws IOException, SftpException {
        String msg = "文件下载成功";

        if (StringUtils.isNullOrEmpty(fileId)) {
            msg = "文件ID<fileId>为空";
            return HttpResult.error(msg);
        }
        // 查询出文件名称来
        InsFileDto dto = insFileMapper.selectByPrimaryKey(fileId);
        if (dto == null) {
            msg = "文件不存在!";
            return HttpResult.error(msg);
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + dto.getNewfilename());
        byte[] buffer = new byte[1024 * 10];
        InputStream fis = null;
        BufferedInputStream bis = null;
        SFTPUtil sftp = null;
        try {
            sftp = new SFTPUtil(upload_username, upload_password, upload_host, 22);
            sftp.login();
            if (!sftp.isExist(dto.getFilepath(), dto.getNewfilename())) {
                msg = "文件不存在";
                return HttpResult.error(msg);
            }
            fis = sftp.download(dto.getFilepath() +FILE_SEPARATOR+ dto.getNewfilename());
            bis = new BufferedInputStream(fis);
            ServletOutputStream out = response.getOutputStream();
            //读取文件流
            int len = 0;
            while ((len = fis.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            sftp.logout();
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    bis = null;
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    fis = null;
                }
            }
        }
        return HttpResult.ok(msg);
    }

    /**
     * 删除文件
     * @param fileId
     * @return
     */
    @Override
    public HttpResult deleteFile(String fileId) throws SftpException {
        String msg = "文件删除成功";
        if (StringUtils.isNullOrEmpty(fileId)) {
            msg = "文件ID<fileId>为空";
            return HttpResult.error(msg);
        }
        // 查询出文件名称来
        InsFileDto dto = insFileMapper.selectByPrimaryKey(fileId);
        if (dto == null) {
            msg = "文件不存在!";
            return HttpResult.error(msg);
        }
        /*SFTPUtil sftp = new SFTPUtil(upload_username, upload_password, upload_host, 22);
        sftp.login();*/
        try {
//            sftp.delete(dto.getFilepath(),dto.getNewfilename());
            insFileMapper.deleteByPrimaryKey(fileId);
            File file = new File(dto.getFilepath());
            deleteFiles(file);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally {
//            sftp.logout();
        }
        return HttpResult.ok(msg);
    }

    /**
     * 文件查询
     *
     * @param dirId
     * @return
     */
    @Override
    public HttpResult select(String dirId) {
        String msg = "文件查询成功";
        if (StringUtils.isNullOrEmpty(dirId)) {
            msg = "文件夹ID<dirId>为空";
            return HttpResult.error(msg);
        }
        // 查询出文件名称来
        List<InsFileDto> dtoList = insFileMapper.selectByDirId(dirId);
        if (dtoList == null || dtoList.size()==0) {
            msg = "文件不存在!";
            return HttpResult.error(msg);
        }

        return HttpResult.ok(msg,dtoList);
    }

    /**
     * 文件查询
     *
     * @param fileid
     * @return
     */
    @Override
    public HttpResult selectFileid(String fileid) {
        String msg = "文件查询成功";
        if (StringUtils.isNullOrEmpty(fileid)) {
            msg = "文件ID<fileid>为空";
            return HttpResult.error(msg);
        }
        // 查询出文件名称来
        List<InsFileDto> dtoList = insFileMapper.selectByFileid(fileid);
        if (dtoList == null || dtoList.size()==0) {
            msg = "文件不存在!";
            return HttpResult.error(msg);
        }

        return HttpResult.ok(msg,dtoList);
    }

    /**
     * 根据DIRID上传文件
     *
     * @param files
     * @param dirId
     * @return
     */
    @Override
    public HttpResult uploadFilesByDirId(MultipartFile[] files, String dirId) throws IOException, SftpException {
        return this.upload(files,dirId,"insagent");
    }

    /**
     * 将BASE64转为文件流上传
     *
     * @param base64Code
     * @param dirId
     * @return
     */
    @Override
    public HttpResult uploadFilesByDirId(String base64Code, String dirId) throws IOException, SftpException {
        File file = base64ToFile(base64Code);

        MultipartFile[] files = new MultipartFile[]{fileToMultipartFile(file)};
        return this.uploadFilesByDirId(files, dirId);
    }


    /**
     * 生成新的文件名
     * @param originalFilename
     * @return
     */
    private String makeFileName(String originalFilename) {
        // 当前毫秒值.原文件类型
        return System.currentTimeMillis()  + originalFilename.substring(originalFilename.lastIndexOf("."));//后缀
    }

    /**
     * 校验文件类型
     * @return
     */
    public void checkFileType(String fileType) {
        if (!("jpg".equalsIgnoreCase(fileType)
                || "jpeg".equalsIgnoreCase(fileType)
                || "png".equalsIgnoreCase(fileType)
                || "docx".equalsIgnoreCase(fileType)
                || "rar".equalsIgnoreCase(fileType)
                || "zip".equalsIgnoreCase(fileType)
                || "xlsl".equalsIgnoreCase(fileType)
                || "doc".equalsIgnoreCase(fileType)
                || "pdf".equalsIgnoreCase(fileType)
                || "txt".equalsIgnoreCase(fileType)
                || "xls".equalsIgnoreCase(fileType)
                || "csv".equalsIgnoreCase(fileType)
                || "ppt".equalsIgnoreCase(fileType)
                || "pptx".equalsIgnoreCase(fileType)
                || "xlsx".equalsIgnoreCase(fileType)
                || "mp4".equalsIgnoreCase(fileType)
                || "mp5".equalsIgnoreCase(fileType)



        )) {
            throw new DescribeException("文件类型校验未通过");
        }
    }

    /**
     * 生成路径
     * @param path
     * @param dirId
     * @return
     */
    private List<String> generatePath(String path, String dirId){
        List<String> paths = new ArrayList<>();
        // 获取目录id  D开头
        if (StringUtils.isNullOrEmpty(dirId)){
            dirId = dualidMapper.GetDirIdNext();
        }
        paths.add(dirId);
        if (StringUtils.isNullOrEmpty(path)){
            path="";
        }else{
            if (path.contains(FILE_SEPARATOR)){
                String[] split = path.split(FILE_SEPARATOR,-1);
                String newPath="";
                for (String s : split) {
                    if ("".equals(s.trim())){
                        continue;
                    }else{
                        newPath+=s+FILE_SEPARATOR;
                    }
                }
                path=newPath;
            }else if(path.contains(FILE_SEPARATOR)){
                String[] split = path.split(FILE_SEPARATOR,-1);
                String newPath="";
                for (String s : split) {
                    if ("".equals(s.trim())){
                        continue;
                    }else{
                        newPath+=s+FILE_SEPARATOR;
                    }
                }
                path=newPath;
            }else{
                path=path+FILE_SEPARATOR;
            }
        }
        paths.add(path);

        return paths;
    }

    /**
     * 文件转BASE64
     * @param file
     * @return
     */
    public static String file2Base64(File file) {
        if(file==null) {
            return null;
        }
        String base64 = null;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            byte[] buff = new byte[fin.available()];
            fin.read(buff);
            base64 = Base64.encode(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    /**
     * Base64转文件
     * @param base64
     * @return
     */
    public static File base64ToFile(String base64) {
        if(base64==null||"".equals(base64)) {
            return null;
        }
        byte[] buff=Base64.decode(base64);
        File file=null;
        FileOutputStream fout=null;
        try {
            file = File.createTempFile(System.currentTimeMillis()+"", ".jpg");
            fout=new FileOutputStream(file);
            fout.write(buff);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fout!=null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * File转MultipartFile类型
     * @param file
     * @return
     * @throws IOException
     */
    public static MultipartFile fileToMultipartFile(File file) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

        return multipartFile;
    }

    /**
     * 删除本地文件夹
     * 如果是文件 ==》直接删除
     * 如果是目录 ==》必须先删除里面每一层目录里的所有文件,最后才能删除外层的目录
     *              原因:不为空的话 删不了
     */
    public void deleteFiles(File file) {
        if(file.exists()) {//判断路径是否存在
            if(file.isFile()){//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                file.delete();
                System.out.println("删除成功");
            }else{//不是文件,对于文件夹的操作
                //保存 路径D:/1/新建文件夹2  下的所有的文件和文件夹到listFiles数组中
                File[] listFiles = file.listFiles();//listFiles方法:返回file路径下所有文件和文件夹的绝对路径
                for (File file2 : listFiles) {
                    /*
                     * 递归作用:由外到内先一层一层删除里面的文件 再从最内层 反过来删除文件夹
                     *    注意:此时的文件夹在上一步的操作之后,里面的文件内容已全部删除
                     *         所以每一层的文件夹都是空的  ==》最后就可以直接删除了
                     */
                    deleteFiles(file2);
                }
            }
            file.delete();
            System.out.println("删除成功");

        }else {
            System.out.println("该file路径不存在!!");
        }
    }

    public static void main(String[] args) {
        File file = new File("D:\\home\\mapper\\modules");
        new UpdownLoadServiceImpl().deleteFiles(file);
    }

}

  1. 文件序号Mapper
package com.ydtech.modules.esm.dao;

import org.springframework.stereotype.Repository;

/**
 * @Author: shixk
 * @create: 2021/9/6 10:51
 * description:
 */
@Repository
public interface DualidMapper {

    /**
     * 获取下一个fileid
     */
    String GetFileIdNext();

    /**
     * 获取下一个fileid
     */
    String GetDirIdNext();

    /**
     * 获取当前fileid
     */
    String GetFileIdNow();

    /**
     * 获取当前fileid
     */
    String GetDirIdNow();

    /**
     * 修改fileid
     */
    String UpdateFileId();

    /**
     * 修改fileid
     */
    String UpdateDirId();


}

  1. XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ydtech.modules.esm.dao.DualidMapper">
  <resultMap id="BaseResultMap" type="com.ydtech.modules.esm.model.DualidDto">
    <id column="fileid" jdbcType="BIGINT" property="fileid" />
    <result column="dirid" jdbcType="BIGINT" property="dirid" />
  </resultMap>
  <sql id="Base_Column_List">
    fileid, dirid
  </sql>
  <update id="UpdateFileId">
    UPDATE dualid
    SET fileid=fileid+1
  </update>
  <update id="UpdateDirId">
     UPDATE dualid
    SET dirid=dirid+1
  </update>
  <select id="GetFileIdNext" resultType="java.lang.String">
      UPDATE dualid SET fileid=fileid+1;
      SELECT CONCAT('F',fileid) AS fileid FROM dualid;
  </select>
  <select id="GetDirIdNext" resultType="java.lang.String">
      UPDATE dualid SET dirid=dirid+1;
      SELECT CONCAT('D',dirid) AS dirid FROM dualid;
  </select>
  <select id="GetFileIdNow" resultType="java.lang.String">
    SELECT CONCAT('F',fileid) AS fileid FROM dualid
  </select>
  <select id="GetDirIdNow" resultType="java.lang.String">
    SELECT CONCAT('D',dirid) AS dirid FROM dualid
  </select>


</mapper>
  1. SFTPUtil工具类
package com.ydtech.utils;

import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

/** 
* 类说明 sftp工具类
*/
public class SFTPUtil {
    private transient Logger log = LoggerFactory.getLogger(this.getClass());
    
    private ChannelSftp sftp;  
        
    private Session session;  
    /** SFTP 登录用户名*/    
    private String username; 
    /** SFTP 登录密码*/    
    private String password;  
    /** 私钥 */    
    private String privateKey;  
    /** SFTP 服务器地址IP地址*/    
    private String host;  
    /** SFTP 端口*/  
    private int port;  
        
    
    /**  
     * 构造基于密码认证的sftp对象  
     */    
    public SFTPUtil(String username, String password, String host, int port) {  
        this.username = username;  
        this.password = password;  
        this.host = host;  
        this.port = port;  
    } 
    
    /**  
     * 构造基于秘钥认证的sftp对象 
     */  
    public SFTPUtil(String username, String host, int port, String privateKey) {  
        this.username = username;  
        this.host = host;  
        this.port = port;  
        this.privateKey = privateKey;  
    }  
    
    public SFTPUtil(){}  
    
    
    /** 
     * 连接sftp服务器 
     */  
    public void login(){  
        try {  
            JSch jsch = new JSch();  
            if (privateKey != null) {  
                jsch.addIdentity(privateKey);// 设置私钥  
            }  
    
            session = jsch.getSession(username, host, port);  
           
            if (password != null) {  
                session.setPassword(password);    
            }  
            Properties config = new Properties();  
            config.put("StrictHostKeyChecking", "no");  
                
            session.setConfig(config);  
            session.connect();  
              
            Channel channel = session.openChannel("sftp");  
            channel.connect();  
    
            sftp = (ChannelSftp) channel;  
        } catch (JSchException e) {  
            e.printStackTrace();
        }  
    }    
    
    /** 
     * 关闭连接 server  
     */  
    public void logout(){  
        if (sftp != null) {  
            if (sftp.isConnected()) {  
                sftp.disconnect();  
            }  
        }  
        if (session != null) {  
            if (session.isConnected()) {  
                session.disconnect();  
            }  
        }  
    }  
 
    
    /**  
     * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
     * @param basePath  服务器的基础路径 
     * @param directory  上传到该目录  
     * @param sftpFileName  sftp端文件名  
     * @param input   输入流
     */  
    public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{  
        try {
            try {
                sftp.cd(basePath);
            }catch (SftpException e){
                String [] dirs=basePath.split("/");
                String tempPath="/";
                for(String dir:dirs){
                    if(null== dir || "".equals(dir)) continue;
                    tempPath+=dir+"/";
                    try{
                        sftp.cd(tempPath);
                    }catch(SftpException ex){
                        sftp.mkdir(tempPath);
                        sftp.cd(tempPath);
                    }
                }
            }
            sftp.cd(directory);
        } catch (SftpException e) { 
            //目录不存在,则创建文件夹
            String [] dirs=directory.split("/");
            String tempPath=basePath;
            for(String dir:dirs){
            	if(null== dir || "".equals(dir)) continue;
            	tempPath+=dir;
            	try{ 
            		sftp.cd(tempPath);
            	}catch(SftpException ex){
            		sftp.mkdir(tempPath);
            		sftp.cd(tempPath);
            	}
            }
        }

        sftp.put(input, sftpFileName);  //上传文件
    }

 
    /** 
     * 下载文件。
     * @param directory 下载目录  
     * @param downloadFile 下载的文件 
     * @param saveFile 存在本地的路径 
     */    
    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{  
        if (directory != null && !"".equals(directory)) {  
            sftp.cd(directory);  
        }  
        File file = new File(saveFile);  
        sftp.get(downloadFile, new FileOutputStream(file));  
    }  
    
    /**  
     * 下载文件 
     * @param directory 下载目录 
     * @param downloadFile 下载的文件名 
     * @return 字节数组 
     */  
    public byte[] download(String directory, String downloadFile) throws SftpException, IOException{  
        if (directory != null && !"".equals(directory)) {  
            sftp.cd(directory);  
        }  
        InputStream is = sftp.get(downloadFile);  
          
        byte[] fileData = IOUtils.toByteArray(is);
          
        return fileData;  
    }

    /**
     * 下载文件
     * @param directory 文件目录
     * @return  返回流
     * @throws SftpException
     */
    public InputStream download(String directory) throws SftpException {
        return sftp.get(directory);
    }
    
    
    /** 
     * 删除文件 
     * @param directory 要删除文件所在目录 
     * @param deleteFile 要删除的文件 
     */  
    public void delete(String basePath,String directory, String deleteFile) throws SftpException{
        sftp.cd(basePath);
        sftp.cd(directory);
        sftp.rm(deleteFile);  
    }

    /**
     * 文件删除
     * @param basePath
     * @param deleteFile
     * @throws SftpException
     */
    public void delete(String basePath, String deleteFile) throws SftpException{
        sftp.cd(basePath);
        sftp.rm(deleteFile);
    }


    /** 
     * 列出目录下的文件 
     * @param directory 要列出的目录
     */  
    public Vector<?> listFiles(String directory) throws SftpException {  
        return sftp.ls(directory);  
    }

    /**
     * 文件是否存在
     * @param serverPath  路径
     * @param folderName  文件名称
     * @return
     */
    public boolean isExist(String serverPath, String folderName) {
        try {
            sftp.cd(serverPath);
            // 判断子目录文件夹是否存在,不存在即创建
            SftpATTRS attrs = null;
            attrs = sftp.stat(folderName);
            if (attrs != null) {
                return true;
            }

        } catch (Exception e) {
            e.getMessage();
            return false;
        }
        return false;
    }


}
  1. POM
<!-- sftp连接 -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>
        <!--File转MultipartFile类型-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.8</version>
        </dependency>
  1. InsFileDto
package com.ydtech.modules.ins.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "文件上传类", description = "文件上传类")
public class InsFileDto {
    /**
     * 文件id
     */
    @ApiModelProperty(value = "文件id")
    private String fileid;

    /**
     * 文件夹id
     */
    @ApiModelProperty(value = "文件夹id")
    private String dirid;

    /**
     * 旧文件名称
     */
    @ApiModelProperty(value = "旧文件名称")
    private String oldfilename;

    /**
     * 新文件名称
     */
    @ApiModelProperty(value = "新文件名称")
    private String newfilename;

    /**
     * 文件路径
     */
    @ApiModelProperty(value = "文件路径")
    private String filepath;

    /**
     * 前端访问路径
     */
    @ApiModelProperty(value = "前端访问路径")
    private String url;

    /**
     * 创建时间
     */
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
    @ApiModelProperty(value = "创建时间")
    private Date ctratetime;

    /**
     * 更新时间
     */
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
    @ApiModelProperty(value = "更新时间")
    private Date updatetime;


}

总结:不是原创,参考了很多人才总结起来的。方便自己以后使用。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值