Use of ftp server

The project often needs to use the upload and download of files. Here, we will introduce the upload and download of files when filezilla is used as the file server. Although filezilla is used as the ftp server, it can be used if it is replaced by other server codes.

First download filezilla, address: https://sourceforge.net/projects/filezilla/files/?source=navbar

Select filezilla server to download, after installation, open the installation path folder as follows:

Note that after opening the filezilla server with the administrator, then click on the filezilla server Interface, and then you can see the following interface:

Click the button in the red box to configure the user and permissions to connect to the server, as shown in the following figure:

Click add to add an account, enter the account name and click ok, then the following figure

Note First click add in the red box to add the main folder, and then the boxes under the files on the right represent the operation permissions of the files, and the directories represent the operation permissions of the folders. After setting, click ok and then set the password and you are done.

Next is the use in the project.

First, the following packages should be included in the pom file:

<!-- 封装了各种网络协议的客户端,支持FTP、NNTP、SMTP、POP3、Telnet等协议 -->
		<dependency>  
            <groupId>commons-net</groupId>  
            <artifactId>commons-net</artifactId>  
            <version>3.1</version>
        </dependency>
        <!-- java上传文件 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2</version>
		</dependency>

Then configure a file parser:

<!-- 配置一个文件上传解析器,此ID是固定的,无法改变的 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 单位是byte,例如:10M=10*1024*1024 当设值为:-1时表示不限制容量 -->
		<property name="maxUploadSize" value="-1"></property>
		<!-- 默认字符集编码 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 每次读取文件时,最大的内存容量 -->
		<property name="maxInMemorySize" value="1024"></property>
	</bean>

Then there is the tool class of ftp:

/**
 * 
 *@description 
 *@auth panmingshuai
 *@time 2018年4月1日上午1:11:27
 *
 */
public class FtpKit {
	// ftp服务器地址
	public static String hostname = "127.0.0.1";
	// ftp服务器端口号默认为21
	public static Integer port = 21;
	// ftp登录账号
	public static String username = "panftp";
	// ftp登录密码
	public static String password = "123456";

	public static FTPClient ftpClient = null;

	/**
	 * 初始化ftp服务器
	 */
	public static void initFtpClient() {
		ftpClient = new FTPClient();
		ftpClient.setControlEncoding("utf-8");
		try {
			ftpClient.connect(hostname, port); // 连接ftp服务器
			ftpClient.login(username, password); // 登录ftp服务器

			int replyCode = ftpClient.getReplyCode(); // 是否成功登录服务器
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				System.out.println("connect failed...ftp服务器:" + hostname + ":" + port);
			}
			System.out.println("connect successfu...ftp服务器:" + hostname + ":" + port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param pathname ftp服务保存地址
	 * @param fileName 上传到ftp的文件名
	 * @param inputStream 输入文件流
	 * @return
	 */
	public static boolean uploadFile(String pathname, String fileName, InputStream inputStream) {
		try {
			initFtpClient();

			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.makeDirectory(pathname);
			ftpClient.changeWorkingDirectory(pathname);
			ftpClient.storeFile(fileName, inputStream);

			inputStream.close();
			ftpClient.logout();
			ftpClient.disconnect();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean existFile(String path) throws IOException {
		initFtpClient();

		FTPFile[] ftpFileArr = ftpClient.listFiles(path);
		if (ftpFileArr.length > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 下载文件
	 * 
	 * @param pathname FTP服务器保存目录 *
	 * @param filename 要删除的文件名称 *
	 * @return
	 */
	public static byte[] downloadFile(String pathname, String filename) {
		try {
			initFtpClient();

			ftpClient.changeWorkingDirectory(pathname);
			FTPFile[] ftpFiles = ftpClient.listFiles();
			for (FTPFile file : ftpFiles) {
				if (filename.equalsIgnoreCase(file.getName())) {
					return IOUtils.toByteArray(ftpClient.retrieveFileStream(file.getName()));
				}
			}
			ftpClient.logout();
			ftpClient.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 删除文件
	 * 
	 * @param pathname FTP服务器保存目录 *
	 * @param filename 要删除的文件名称 *
	 * @return
	 */
	public static boolean deleteFile(String pathname, String filename) {
		try {
			initFtpClient();

			ftpClient.changeWorkingDirectory(pathname);
			ftpClient.dele(filename);
			ftpClient.logout();
			ftpClient.disconnect();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}


}

Then the controller:

/**
 * 
 *@description 
 *@auth panmingshuai
 *@time 2018年4月1日上午1:11:27
 *
 */
@Controller
@RequestMapping("test")
public class TestController {
	
	/**
	 * 上传文件
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public ReturnModel upload(MultipartFile file) throws IOException {
		if (file != null) {
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String fileName = UUID.randomUUID().toString() + suffix;
			//指定上传的文件要放到data文件夹下,fileName是存放文件的名字
			FtpKit.uploadFile("data", fileName, file.getInputStream());
			return new ReturnModel(ReturnModel.SUCCESS_CODE, "上传成功");
		}
		return new ReturnModel(ReturnModel.SUCCESS_CODE, "上传失败");
	}
	
	/**
	 * 下载
	 * @param fileId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/download")  
	public void downPhotoByStudentId(String fileId, final HttpServletResponse response) throws IOException{  
	    
	    response.reset();  
	    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileId + "\"");  //设置文件名
	    response.addHeader("Content-Length", "" + "879394");  //设置文件大小,以B为单位
	    response.setContentType("application/octet-stream;charset=UTF-8");  
	    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
	    //指明要从哪个文件夹下寻找文件
	    outputStream.write(FtpKit.downloadFile("data", fileId));  
	    outputStream.flush();  
	    outputStream.close(); 
	} 
}

complete.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325441684&siteId=291194637