服务器上传下载文件

导读:本篇文章讲解 服务器上传下载文件,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

wen请求过来直接上传至服务器 通过nginx 返回 预览url 下载通过文件名直接下载
工具类

package com.example.guowang.utill;

import java.io.*;
import java.util.Properties;
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletResponse;

/**
 * 实现FTP文件上传和文件下载
 */
 
	@Configuration
	public class FtpApche {

    //服务器路径
    @Value("${ftp.url}")
    private  String url;

    //服务器端口号
    @Value("${ftp.port}")
    private int port;


    //用户名
    @Value("${ftp.username}")
    private String username;


    //密码
    @Value("${ftp.password}")
    private String password;

    /**
     * FTPClient对象
     **/
    private static ChannelSftp ftpClient = null;
    /**
     *
     */
    private static Session sshSession = null;

    /**
     * 连接服务器
     *
     * @return
     * @throws Exception
     */
    public  ChannelSftp getConnect()
            throws Exception {
        try {

        JSch jsch = new JSch();
        // 获取sshSession
        sshSession = jsch.getSession(username, url, port);
        // 添加s密码
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        System.out.println("开始连接.........");


        // 开启sshSession链接
        sshSession.connect();
        // 获取sftp通道
        ftpClient = (ChannelSftp) sshSession.openChannel("sftp");
        // 开启
        ftpClient.connect();
        System.err.println("success ..........");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("连接sftp服务器异常。。。。。。。。");
        }
        return ftpClient;
	    }

	    /**
	     * 下载文件
	     * @param directory 下载目录
	     * @param downloadFile 下载的文件名
	     *
	     */
	
	   	 public static void download(String directory, String downloadFile,HttpServletResponse response) throws SftpException, IOException {
	        if (directory != null && !"".equals(directory)) {
	            ftpClient.cd(directory);
	        }
	        InputStream is = ftpClient.get(downloadFile);

        if (is != null) {
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + downloadFile);
            byte[] buffer = new byte[1024];

            BufferedInputStream bis = null;
            try {

            bis = new BufferedInputStream(is);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (IOException e) {

        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

	    /**
	     * 上传
	     * @param ftp_path	服务器保存路径
	     * @param newFileName	新文件名
	     * @throws Exception
	     */
	    public static void uploadFile( InputStream in, String ftp_path,String newFileName) throws Exception {
	        try {
	            ftpClient.cd(ftp_path);
	            ftpClient.put(in, newFileName);
	
	        } catch (Exception e) {
	            e.printStackTrace();
	            throw new Exception("Upload file error.");
	        }
	    }

	    /**
	     * 关闭
	     *
	     * @throws Exception
	     */
	    public static void close() throws Exception {
	        System.err.println("close............");
	        try {
	            ftpClient.disconnect();
	            sshSession.disconnect();
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            throw new Exception("close stream error.");
	        }
	    }
	}

Service 层

	package com.example.guowang.service.imp;
	import com.example.guowang.utill.FtpApche;
	import com.example.guowang.utill.JsonResult;
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.beans.factory.annotation.Value;
	import org.springframework.stereotype.Service;
	import javax.servlet.http.HttpServletResponse;
	import java.io.*;

@Service
public class FileServiceImp  {
    //文件的存放路径
    @Value("${file.uppath}")
    private String localUploadPath;
    //文件的下载路径
    @Value("${file.downpath}")
    private String localDownloadPath;
    @Value("${image.url}")
    private String imageUrl;
    @Autowired
    private FtpApche ftpApche;



/**


 *@param: @param directory 上传文件的目录,即服务端的目录
 *@param: @param uploadFile 将要上传的文件,本地文件
 *@return: void
 */
public JsonResult uploadFile( InputStream in,String filename) {

    try{
        //连接FTP
        ftpApche.getConnect();
        String suffix=filename.substring(filename.lastIndexOf("."));
        String newFileName=System.currentTimeMillis()+suffix;
        //文件上传
        FtpApche.uploadFile(in,localUploadPath,newFileName);
        //连接FTP
        FtpApche.close();
        String newImagePage=imageUrl+newFileName;
        return JsonResult.ok(newImagePage);
    }catch (Exception e){
        e.printStackTrace();
        return  JsonResult.error("上传失败");
    }

}
/*
文件下载
 */
public void downloadFile( String fileName, HttpServletResponse response) {
    try{
        //连接FTP
        ftpApche.getConnect();
        FtpApche.download(localDownloadPath,fileName,response);
        //连接FTP
        FtpApche.close();
    }catch (Exception e){
        e.printStackTrace();
    }
}

}

Controller 层

@ApiOperation(value = "上传文件")
@PostMapping(value = "/up")
public JsonResult  uploadFile(@RequestParam("file") MultipartFile file){
    try{
        InputStream inputStream=file.getInputStream();
        return fileService.uploadFile(inputStream,file.getOriginalFilename());
    }catch (Exception e){
        e.printStackTrace();
        return  JsonResult.error("上传失败");
    }


}
   @ApiOperation(value = "下载文件")
    @PostMapping(value = "/down")
    public void downloadFile(@RequestParam("filename") String fileName, HttpServletResponse response){
        fileService.downloadFile(fileName,response);
    }

启动项

package com.example.guowang;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.unit.DataSize;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.MultipartConfigElement;

@SpringBootApplication
@MapperScan(basePackages= "com.example.guowang.mapper")
@EnableTransactionManagement
@Configuration
public class GuowangApplication {

public static void main(String[] args) {
    SpringApplication.run(GuowangApplication.class, args);
}


@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    //  单个数据大小
    factory.setMaxFileSize(DataSize.parse("100MB")); // KB,MB
    /// 总上传数据大小
    factory.setMaxRequestSize(DataSize.parse("100MB"));
    return factory.createMultipartConfig();
}

}

依赖

 <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.55</version>
    </dependency>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15578.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!