上传文件的几种方式

上传文件,归根结底还是使用字符流对文件操作

  • 文件共享方式

文件共享,首先需要设置共享文件夹,自行度娘

  • 映射网络驱动

设置驱动,相当于本地盘符

设置关联共享文件夹路径(格式:\\+ip+\+共享名称)

网络映射配置完成,上传文件使用流方式写入上图设置的驱动Y:

  • SMB协议

SMB(全称是Server Message Block)是一个协议名,它能被用于Web连接和客户端与服务器之间的信息沟通。

创建SMB类

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import fxms.com.autotask.work.clientAndAccount.clientAndAccountDatasynTask;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import log.OSPLogger;

/**
 * 
 * @ClassName: Smb
 * @Description: 远程共享文件操作类
 */
public class Smb {
	private static OSPLogger log = OSPLogger.getLogger(clientAndAccountDatasynTask.class);
	private String url = "";
	private SmbFile smbFile = null;
	private SmbFileOutputStream smbOut = null;
	private static Smb smb = null; // 共享文件协议

	public static Smb getInstance(String url) {
		if (smb == null)
			return new Smb(url);
		return smb;
	}

	public Smb(String url) {
		this.url = url;
		this.init();
	}

	/**
	 * 
	 * @Title: init
	 * @Description: 初始化,获取连接 
	 * @return: void
	 */
	public void init() {
		try {
			log.info("开始连接...url:" + this.url);
			smbFile = new SmbFile(this.url);
			smbFile.connect();
			log.info("连接成功...url:" + this.url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			log.error(e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e);
		}
	}

	/**
	 * 
	 * @Title: uploadFile @Description: 上传文件 @param @param file @param @return
	 *         参数 @return int 返回类型 @throws
	 */
	public int uploadFile(File file) {
		int flag = -1;
		BufferedInputStream bf = null;
		try {
			smbOut = new SmbFileOutputStream(this.url + "/" + file.getName(), false);
			bf = new BufferedInputStream(new FileInputStream(file));
			byte[] bt = new byte[8192];
			int n = bf.read(bt);
			while (n != -1) {
				this.smbOut.write(bt, 0, n);
				this.smbOut.flush();
				n = bf.read(bt);
			}
			flag = 0;
			log.info("文件传输结束...");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		} finally {
			try {
				if (null != this.smbOut)
					this.smbOut.close();
				if (null != bf)
					bf.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return flag;
	}

	/**
	 * 
	 * @Title: deleteSmbFile @Description: 删除文件 @param @param url @param @throws
	 * MalformedURLException @param @throws SmbException 参数 @return void
	 * 返回类型 @throws
	 */
	public void deleteSmbFile(String url) throws MalformedURLException, SmbException {
		SmbFile file = new SmbFile(url);
		if (file.exists()) {
			file.delete();
		}
	}
	
	//注:使用SMB协议,所有对文件的操作都要通过此协议
}

文件操作类

public class YHDZDUploadService {
    public YHDZDUploadService(){};

    // 共享路径
    // 格式: smb://有权限的用户:密码@共享路径
    public static final String BASEPATH = "smb://admin:admin@127.0.0.1/shar/";//参数一般放配置

    /**
	 * 
	 * @Title: uploadFile @Description: 上传文件 @param @param file @param @return
	 *         参数 @return int 返回类型 @throws
	 */
	public int uploadFile(File file) {
		int flag = -1;
		BufferedInputStream bf = null;
		try {
			smbOut = new SmbFileOutputStream(this.url + "/" + file.getName(), false);
			bf = new BufferedInputStream(new FileInputStream(file));
			byte[] bt = new byte[8192];
			int n = bf.read(bt);
			while (n != -1) {
				this.smbOut.write(bt, 0, n);
				this.smbOut.flush();
				n = bf.read(bt);
			}
			flag = 0;
			log.info("文件传输结束...");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		} finally {
			try {
				if (null != this.smbOut)
					this.smbOut.close();
				if (null != bf)
					bf.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return flag;
	}

	/**
	 * 
	 * @Title: deleteSmbFile @Description: 删除文件 @param @param url @param @throws
	 * MalformedURLException @param @throws SmbException 参数 @return void
	 * 返回类型 @throws
	 */
	public void deleteSmbFile(String url) throws MalformedURLException, SmbException {
		SmbFile file = new SmbFile(url);
		if (file.exists()) {
			file.delete();
		}
	}

}

 

  • FTP方式

1、安装FTP服务端(安装配置不赘述,参考其他博主,这个比较详细https://blog.csdn.net/l101606022/article/details/79944576

2、后台编码

//1、添加依赖
//	<dependency>
//	    <groupId>commons-net</groupId>
//	    <artifactId>commons-net</artifactId>
//	    <version>3.1</version>
//    </dependency>


//2、上传方法
/**
	 * 
	 * @Title: upload
	 * @Description: ftp文件上传
	 * @param file
	 * @return: void
	 */
	public void upload(File file){
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect("1.1.1.1",21);//设置地址和端口号
            ftp.login("aaa", "bbb");//用户名和密码
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//上传文件类型 二进制文件
            int reply = ftp.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){//检查连接是否有效
                System.out.println("error");
                return;
            }
            ftp.changeWorkingDirectory("/test");
            FileInputStream fis = new FileInputStream(file);
            ftp.storeFile(file.getName(), fis);//关键代码,把流持久化到硬盘上
            fis.close();
            ftp.logout();
            ftp.disconnect();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

/**
	 * 
	 * @Title: downloadFile
	 * @Description: 下载文件
	 * @param pathname
	 * @param filename
	 * @param localpath
	 * @return
	 * @return: boolean
	 */
	 public static boolean downloadFile(String pathname, String filename, String localpath){ 
         boolean flag = false; 
         OutputStream os=null;
         log.info("开始下载文件!");
         try { 
             initFtpClient();
             //切换FTP目录 
             ftpClient.changeWorkingDirectory(pathname); 
             FTPFile[] ftpFiles = ftpClient.listFiles(); 
             for(FTPFile file : ftpFiles){ 
                 if(filename.equalsIgnoreCase(file.getName())){ 
                     File localFile = new File(localpath + "/" + file.getName()); 
                     os = new FileOutputStream(localFile); 
                     ftpClient.retrieveFile(file.getName(), os); 
                     os.close(); 
                 } 
             } 
             ftpClient.logout(); 
             flag = true; 
             log.info("下载文件成功");
         } catch (Exception e) { 
        	 log.info("下载文件失败");
             e.printStackTrace(); 
         } finally{ 
             if(ftpClient.isConnected()){ 
                 try{
                     ftpClient.disconnect();
                 }catch(IOException e){
                     e.printStackTrace();
                 }
             } 
             if(null != os){
                 try {
                     os.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 } 
             } 
         } 
         return flag; 
     }
     
     /**
      * 
      * @Title: deleteFile
      * @Description: 删除文件
      * @param pathname
      * @param filename
      * @return
      * @return: boolean
      */
     public boolean deleteFile(String pathname, String filename){ 
         boolean flag = false; 
         try { 
             log.info("开始删除文件");
             initFtpClient();
             //切换FTP目录 
             ftpClient.changeWorkingDirectory(pathname); 
             ftpClient.dele(filename); 
             ftpClient.logout();
             flag = true; 
             log.info("删除文件成功");
         } catch (Exception e) { 
        	 log.info("删除文件失败");
             e.printStackTrace(); 
         } finally {
             if(ftpClient.isConnected()){ 
                 try{
                     ftpClient.disconnect();
                 }catch(IOException e){
                     e.printStackTrace();
                 }
             } 
         }
         return flag; 
     }

 

  • 框架自带

SpringMVC

1、springmvc.xml配置
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--上传文件的最大大小,单位为字节 --> 
    <property name="maxUploadSize" value="17367648787"></property>
     
    <!-- 上传文件的编码 -->
    <property name="defaultEncoding" value="UTF-8"></property>
</bean>

2、后台实现
public static final String UPPATH = "";//配置
	
	@RequestMapping("/upload")
	public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
	        throws IllegalStateException, IOException {

	    if (file.isEmpty()) {
	        return "failed";
	    }
	    String path = req.getServletContext().getRealPath(UPPATH);
	    // 获取原文件名
	    String fileName = file.getOriginalFilename();
	    // 创建文件实例
	    File filePath = new File(path, fileName);
	    // 如果文件目录不存在,创建目录
	    if (!filePath.getParentFile().exists()) {
	        filePath.getParentFile().mkdirs();
	        System.out.println("创建目录" + filePath);
	    }
	    // 写入文件
	    file.transferTo(filePath);
	    return "success";
	}  

框架还有status等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值