ftp服務器的使用

項目中常常須要使用到文件的上傳下載,這裏介紹一下以filezilla做爲文件服務器時,文件的上傳和下載,雖然是使用filezilla做爲ftp服務器,可是若是換爲其餘服務器代碼是同樣可使用的。java

首先下載filezilla,地址:https://sourceforge.net/projects/filezilla/files/?source=navbarweb

選擇filezilla server下載,安裝好之後,打開安裝路徑文件夾以下:spring

注意用管理員打開filezilla server後,而後點開filezilla server Interface,而後能夠看到以下界面:服務器

點擊紅框中的按鈕,能夠配置鏈接服務端的用戶和權限,以下圖所示:網絡

點擊add添加帳號,輸入帳號名字點擊ok,而後以下圖app

注先點擊紅框中的add添加主文件夾,而後右邊的files下面的幾個框表明文件的操做權限,directories表明文件夾的操做權限。設置好之後點擊ok而後設置密碼以後就完事了。dom

接着是項目中的使用。工具

首先pom文件中要有如下的包:編碼

<!-- 封裝了各類網絡協議的客戶端,支持FTP、NNTP、SMTP、POP三、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>

接着配置一個文件解析器:.net

<!-- 配置一個文件上傳解析器,此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>

而後是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;
	}


}

而後是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(); 
	} 
}

完畢。

相關文章
相關標籤/搜索