栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

文件上传和下载

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

文件上传和下载

使用阿里云服务器

上传

controller层:

    
    @Value("${ctj.fineReport.host}")
    private String ip;
    @Value("${ctj.fineReport.port}")
    private int port;
    @Value("${ctj.fineReport.username}")
    private String username;
    @Value("${ctj.fineReport.password}")
    private String password;
    @Value("${ctj.fineReport.path}")
    private String path;

    @ApiOperation(value = "文件上传(江苏预算执行报表文件)")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultData upload(@RequestParam(value = "file") MultipartFile file,
                                      @RequestParam String admDivCode,
                                      @RequestParam int busiYear) {
        try {
            Ftp ftp = Ftp.getSftpUtil(ip, port, username, password);
            
            File file1 = multipartFileToFile(file);
            String fileName = file.getOriginalFilename().trim();
            String destFileName = "/" + admDivCode + "/" + busiYear + "/" + path;
            fileName = URLDecoder.decode(fileName, "UTF-8");
            destFileName = URLDecoder.decode(destFileName, "UTF-8");
            
            ftp.upload(destFileName, file1, ftp, fileName);

            Report report = new Report();
            String id = UUID.randomUUID().toString().replace("-", "");
            report.setReport_id(id);
            report.setReport_name(fileName);
            report.setTenant_id(Integer.valueOf(admDivCode));
            report.setUpdate_time(new Date());
            report.setIs_deleted(2);
            
            reportMapper.insertReport(report);
            
            return new ResultData("0000", "上传成功", true);
        } catch (Exception e) {
            logger.error("上传失败,异常信息:{}", e.getMessage(), e);
            return new ResultData("9999", "上传失败:" + e.getMessage(), null);
        }

    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            logger.error("获取流文件失败!", e.getMessage(), e);
        }
    }

yml配置文件

### 配置类参数
ctj:
  # 判断文件上传类型
  fileTypes:
    - html
    - jsp
    - js
    - css
    - php
    - py
    - sh
  fineReport:
    host: 39.101.189.62
    port: 22
    username: root
    password: 密码
    path: 1

ftp工具类:

下来记得粘贴上来!!!


mapper层:

@Insert("insert into GAP_REPORT (report_id ,report_name ,tenant_id ,update_time,is_deleted) values ("
            + "#{report.report_id, jdbcType=VARCHAR},"
            + "#{report.report_name, jdbcType=VARCHAR},"
            + "#{report.tenant_id, jdbcType=INTEGER},"
            + "#{report.update_time, jdbcType=DATE},"
            + "#{report.is_deleted, jdbcType=INTEGER}"
            + ")")
Boolean insertReport(@Param("report") Report report);
下载

controller层:

    
    @ApiOperation(value = "文件下载(江苏预算执行报表文件)")
    @GetMapping("/download/{id}")
    public void downloadCacheFile(@PathVariable("id") String id,
                                  @RequestParam String admDivCode,
                                  @RequestParam int busiYear,
                                  HttpServletResponse response) {
        try {
            String fileName = reportMapper.selectOneReportName(id);
            String fpath = "/" + admDivCode + "/" + busiYear + "/" + path + "/";
            SFTPUtil sFTPUtil = new SFTPUtil(ip, port, username, password);
            sFTPUtil.connect();
            sFTPUtil.downloadFile(fpath, fileName, response);
        } catch (Exception e) {
            logger.error("下载失败,异常信息:{}", e.getMessage(), e);
        }
    }

mapper层:

@Select("select report_name from GAP_REPORT where report_id = #{id}")
String selectOneReportName(@Param("id") String id);

SFTPUtil工具类:

package grp.pt.frs.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Properties;

@Data
public class SFTPUtil {
    private String host;//服务器连接ip
    private String username;//用户名
    private String password;//密码
    private int port;//端口号
    private ChannelSftp sftp = null;
    private Session sshSession = null;

    public SFTPUtil(){}

    public SFTPUtil(String host, int port, String username, String password)
    {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
    }

    public SFTPUtil(String host, String username, String password)
    {
        this.host = host;
        this.username = username;
        this.password = password;
    }

    
    public void connect()
    {
        try
        {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    
    public void disconnect()
    {
        if (this.sftp != null)
        {
            if (this.sftp.isConnected())
            {
                this.sftp.disconnect();
            }
        }
        if (this.sshSession != null)
        {
            if (this.sshSession.isConnected())
            {
                this.sshSession.disconnect();
            }
        }
    }


    
    public void deleteSFTP(String directory, String deleteFile)
    {
        try
        {
            sftp.rm(directory + deleteFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public void downloadFile(String remotePath, String remoteFileName, HttpServletResponse response) {
        byte[] buf = new byte[1024];
        // 获取输出流
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String rfileName = URLDecoder.decode(remotePath + remoteFileName, "UTF-8");
            InputStream in = sftp.get(rfileName);
            response.reset();
            // 不同类型的文件对应不同的MIME类型
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(remoteFileName, "UTF-8"));

                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }

            out.close();

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


}


附录 stfp下载的工具类(支持批量下载和打包)SFTPUtil
package com.fine.tools.utils;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;

import javax.servlet.http.HttpServletResponse;

public class SFTPUtil {
	private String host = "127.0.0.1";//服务器连接ip
	private String username = "root";//用户名
	private String password = "123";//密码
	private int port = 22;//端口号
	private ChannelSftp sftp = null;
	private Session sshSession = null;

	public SFTPUtil(){}

	public SFTPUtil(String host, int port, String username, String password)
	{
		this.host = host;
		this.username = username;
		this.password = password;
		this.port = port;
	}

	public SFTPUtil(String host, String username, String password)
	{
		this.host = host;
		this.username = username;
		this.password = password;
	}

	
	public void connect()
	{
		try
		{
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			sshSession = jsch.getSession(username, host, port);
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	
	public void disconnect()
	{
		if (this.sftp != null)
		{
			if (this.sftp.isConnected())
			{
				this.sftp.disconnect();
			}
		}
		if (this.sshSession != null)
		{
			if (this.sshSession.isConnected())
			{
				this.sshSession.disconnect();
			}
		}
	}

	
	public List batchDownLoadFile(String remotePath, String localPath,
										  String fileFormat, String fileEndFormat, boolean del)
	{
		List fileList = new ArrayList();
		File file = null;
		try
		{
			Vector v = listFiles(remotePath);
			if (v.size() > 0)
			{
				Iterator it = v.iterator();
				while (it.hasNext())
				{
					LsEntry entry = (LsEntry) it.next();
					String filename = entry.getFilename();
					SftpATTRS attrs = entry.getAttrs();
					if (!attrs.isDir())
					{
						fileFormat = fileFormat == null ? "" : fileFormat
								.trim();
						fileEndFormat = fileEndFormat == null ? ""
								: fileEndFormat.trim();
						// 三种情况
						if (fileFormat.length() > 0 && fileEndFormat.length() > 0)
						{
							if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat))
							{
								file = downloadFile(remotePath, filename,localPath, filename);
								if (file!=null)
								{
									fileList.add(file);
									if (file!=null && del)
									{
										deleteSFTP(remotePath, filename);
									}
								}
							}
						}
						else if (fileFormat.length() > 0 && "".equals(fileEndFormat))
						{
							if (filename.startsWith(fileFormat))
							{
								file = downloadFile(remotePath, filename, localPath, filename);
								if (file!=null)
								{
									fileList.add(file);
									if (file!=null && del)
									{
										deleteSFTP(remotePath, filename);
									}
								}
							}
						}
						else if (fileEndFormat.length() > 0 && "".equals(fileFormat))
						{
							if (filename.endsWith(fileEndFormat))
							{
								file = downloadFile(remotePath, filename,localPath, filename);
								if (file!=null)
								{
									fileList.add(file);
									if (file!=null && del)
									{
										deleteSFTP(remotePath, filename);
									}
								}
							}
						}
						else
						{
							file = downloadFile(remotePath, filename,localPath, filename);
							if (file!=null)
							{
								fileList.add(file);
								if (file!=null && del)
								{
									deleteSFTP(remotePath, filename);
								}
							}
						}
					}
				}
			}
		}
		catch (SftpException e)
		{
			e.printStackTrace();
		}
		return fileList;
	}

	
	public File downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
	{
		FileOutputStream fieloutput = null;
		File file = null;
		try
		{
			file = new File(localPath + localFileName);
			fieloutput = new FileOutputStream(file);
			sftp.get(remotePath + remoteFileName, fieloutput);
			fieloutput.close();
			return file;
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (SftpException e)
		{
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally
		{
			if (null != fieloutput)
			{
				try
				{
					fieloutput.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return file;
	}

	public InputStream downloadStream(String directory, String downloadFile){
		try{
			if(directory != null && !"".equals(directory)){
				sftp.cd(directory);
			}
			return sftp.get(downloadFile);
		}catch (SftpException e){
			e.printStackTrace();
		}
		return null;
	}


	
	public boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
	{
		FileInputStream in = null;
		try
		{
			createDir(remotePath);
			File file = new File(localPath + localFileName);
			in = new FileInputStream(file);
			sftp.put(in, remoteFileName);
			return true;
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (SftpException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (in != null)
			{
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return false;
	}

	
	public boolean bacthUploadFile(String remotePath, String localPath,
								   boolean del)
	{
		try
		{
			connect();
			File file = new File(localPath);
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++)
			{
				if (files[i].isFile()
						&& files[i].getName().indexOf("bak") == -1)
				{
					if (this.uploadFile(remotePath, files[i].getName(),
							localPath, files[i].getName())
							&& del)
					{
						deleteFile(localPath + files[i].getName());
					}
				}
			}
			return true;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			this.disconnect();
		}
		return false;

	}

	
	public boolean deleteFile(String filePath)
	{
		File file = new File(filePath);
		if (!file.exists())
		{
			return false;
		}

		if (!file.isFile())
		{
			return false;
		}
		boolean rs = file.delete();
		return rs;
	}

	
	public boolean createDir(String createpath)
	{
		try
		{
			if (isDirExist(createpath))
			{
				this.sftp.cd(createpath);
				return true;
			}
			String pathArry[] = createpath.split("/");
			StringBuffer filePath = new StringBuffer("/");
			for (String path : pathArry)
			{
				if (path.equals(""))
				{
					continue;
				}
				filePath.append(path + "/");
				if (isDirExist(filePath.toString()))
				{
					sftp.cd(filePath.toString());
				}
				else
				{
					// 建立目录
					sftp.mkdir(filePath.toString());
					// 进入并设置为当前目录
					sftp.cd(filePath.toString());
				}

			}
			this.sftp.cd(createpath);
			return true;
		}
		catch (SftpException e)
		{
			e.printStackTrace();
		}
		return false;
	}

	
	public boolean isDirExist(String directory)
	{
		boolean isDirExistFlag = false;
		try
		{
			SftpATTRS sftpATTRS = sftp.lstat(directory);
			isDirExistFlag = true;
			return sftpATTRS.isDir();
		}
		catch (Exception e)
		{
			if (e.getMessage().toLowerCase().equals("no such file"))
			{
				isDirExistFlag = false;
			}
		}
		return isDirExistFlag;
	}

	
	public void deleteSFTP(String directory, String deleteFile)
	{
		try
		{
			sftp.rm(directory + deleteFile);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	
	public static void zipFiles(List srcfile, String zipFileName, HttpServletResponse response) throws IOException {
		byte[] buf = new byte[1024];
		// 获取输出流
		BufferedOutputStream bos = null;
		try {
			bos = new BufferedOutputStream(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileInputStream in = null;
		ZipOutputStream out = null;
		try {
			response.reset();
			// 不同类型的文件对应不同的MIME类型
			response.setContentType("application/x-msdownload");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName + ".zip", "UTF-8"));

			// ZipOutputStream类:完成文件或文件夹的压缩
			out = new ZipOutputStream(bos);
			for (int i = 0; i < srcfile.size(); i++) {
				in = new FileInputStream(srcfile.get(i));
				// 给列表中的文件单独命名
				out.putNextEntry(new ZipEntry(srcfile.get(i).getName()));
				int len = -1;
				while ((len = in.read(buf)) != -1) {
					out.write(buf, 0, len);
				}
			}
			out.close();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) in.close();
			if (out != null) out.close();
		}
	}

	
	public Vector listFiles(String directory) throws SftpException
	{
		return sftp.ls(directory);
	}

	public String getHost()
	{
		return host;
	}

	public void setHost(String host)
	{
		this.host = host;
	}

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public int getPort()
	{
		return port;
	}

	public void setPort(int port)
	{
		this.port = port;
	}

	public ChannelSftp getSftp()
	{
		return sftp;
	}

	public void setSftp(ChannelSftp sftp)
	{
		this.sftp = sftp;
	}

}


操作本地文件的工具类
package com.fine.tools.utils;

import java.io.File;


public class LocalUtil {

    //创建本地文件夹
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    //删除文件夹
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下的所有文件
    public static boolean delAllFile(String path) throws InterruptedException {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                //由于关闭io流后文件仍然被占用,因此直接采用gc垃圾回收等待两秒删除
                System.gc();
                Thread.sleep(2000);
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

}

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

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

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