天天看點

上傳圖檔檔案到ftp伺服器

效果圖 :

上傳圖檔檔案到ftp伺服器

注 : ftp伺服器的搭建及建立賬号請自行百度 , 這裡主要介紹圖檔上傳的實作

圖檔上傳工具類 :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUtil {
	    /**  
	     * Description: 向FTP伺服器上傳檔案  
	     * @param host FTP伺服器hostname  
	     * @param port FTP伺服器端口  
	     * @param username FTP登入賬号  
	     * @param password FTP登入密碼  
	     * @param basePath FTP伺服器基礎目錄 
	     * @param filePath FTP伺服器檔案存放路徑。例如分日期存放:/2017/12/12。檔案的路徑為basePath+filePath 
	     * @param filename 上傳到FTP伺服器上的檔案名  
	     * @param input 輸入流  
	     * @return 成功傳回true,否則傳回false  
	     */    
	    public static boolean uploadFile(String host, int port, String username, String password, String basePath,  
	            String filePath, String filename, InputStream input) {  
	        boolean result = false;  
	        FTPClient ftp = new FTPClient();  
	        ftp.setControlEncoding("UTF-8");
	        try {  
	            int reply;  
	            ftp.connect(host, port);// 連接配接FTP伺服器  
	            // 如果采用預設端口,可以使用ftp.connect(host)的方式直接連接配接FTP伺服器  
	            ftp.login(username, password);// 登入  
	            reply = ftp.getReplyCode();  
	            if (!FTPReply.isPositiveCompletion(reply)) {  
	                ftp.disconnect();  
	                return result;  
	            }  
	            //切換到上傳目錄  
	            if (!ftp.changeWorkingDirectory(basePath+filePath)) {  
	                //如果目錄不存在建立目錄  
	                String[] dirs = filePath.split("/");  
	                String tempPath = basePath;  
	                for (String dir : dirs) {  
	                    if (null == dir || "".equals(dir)) continue;  
	                    tempPath += "/" + dir;  
	                    if (!ftp.changeWorkingDirectory(tempPath)) {  
	                        if (!ftp.makeDirectory(new String(tempPath.getBytes("UTF-8"),"iso-8859-1"))) {  
	                            return result;  
	                        } else {  
	                            ftp.changeWorkingDirectory(tempPath);  
	                        }  
	                    }  
	                }  
	            }  
	            //設定上傳檔案的類型為二進制類型  
	            ftp.setFileType(FTP.BINARY_FILE_TYPE);  
	            //上傳檔案  
	            ftp.enterLocalPassiveMode();
	            if (!ftp.storeFile(filename, input)) {
	                return result;  
	            }  
	            input.close();  
	            ftp.logout();  
	            result = true;  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } finally {  
	            if (ftp.isConnected()) {  
	                try {  
	                    ftp.disconnect();  
	                } catch (IOException ioe) {  
	                }  
	            }  
	        }  
	        return result;  
	    }
           

在service層内建立接口及接口實作類

public interface PictureService {
	
	Map uploadPicture(MultipartFile uploadFile);

}
           
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.demo.service.PictureService;
import com.demo.util.FtpUtil;
import com.demo.util.IDUtil;
@Service
public class PictureServiceImpl implements PictureService {  
	  
    //擷取ip位址  
    private static final String FTP_ADDRESS = "填寫自己伺服器的外網ip位址";  
    //端口号  
    private static final int FTP_PORT = 21; 
    //使用者名  
    private static final String FTP_USERNAME = "ftp伺服器賬号";  
    //密碼  
    private static final String FTP_PASSWORD = "密碼";  
    //基本路徑  
    private static final String FTP_BASEPATH = "\\";  
    //下載下傳位址的基礎url  
    private static final String IMAGE_BASE_URL = "http://ip位址/ftp";  
  
    @Override  
    public Map uploadPicture(MultipartFile uploadFile) {  
        Map map = new HashMap(); 
  
        try {  
            // 生成一個檔案名  
            // 擷取舊的名字  
            String oldName = uploadFile.getOriginalFilename();  
            String newName = IDUtil.genImageName();  
            //新名字  
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //上傳的路徑  
            SimpleDateFormat df = new SimpleDateFormat("/yyyy/MM/dd/"); //以日期建立檔案夾利于管理
            String imagePath = df.format(new Date());    //目前系統時間保證檔案名不重複
            String ftp = "ftp://";
            String url = ftp + FTP_ADDRESS + imagePath + newName;
            System.out.println("圖檔通路路徑 : " + url);
            //端口号
            int port = FTP_PORT; 
            //調用方法,上傳檔案  
            boolean result = FtpUtil.uploadFile(FTP_ADDRESS, port,  
                    FTP_USERNAME, FTP_PASSWORD, FTP_BASEPATH, imagePath,  
                    newName, uploadFile.getInputStream());  
            //判斷是否上傳成功  
            if (!result) {  
            	map.put("code", 0);
            	map.put("msg", "上傳失敗");
                return map;  
            }  
            map.put("code", 1);
            map.put("msg", "上傳成功");
            map.put("url", url);
            return map;   
  
        } catch (IOException e) { 
        	map.put("code", 0);
        	map.put("msg", "上傳失敗");
            return map; 
        }  
    }  
}  
           

實際調用 :

@RequestMapping(value = "insert_detail")
	public String insert_detail(
			@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value = "productOne", required = false) MultipartFile productOne,
			@RequestParam(value = "productTwo", required = false) MultipartFile productTwo,
			@RequestParam(value = "productThree", required = false) MultipartFile productThree,
			@RequestParam(value = "productFour", required = false) MultipartFile productFour,
			@RequestParam(value = "productFive", required = false) MultipartFile productFive,
			@RequestParam(value = "productSix", required = false) MultipartFile productSix,
			ShopDetail shopdetail) {
		Login user = (Login) request.getSession().getAttribute("user");
		String createCode = String.valueOf(user.getId());
		String createName = user.getRealname();
		//控制流程可以忽略 根據自己的業務來編寫
		if(!file.isEmpty()){
			Map map = pictureService.uploadPicture(file);
			String ftpPath = (String) map.get("url");
			String posPath = ftpPath.substring(20);
			String url = FRONTPATH + posPath;
			shopdetail.setUrl(url);
		}
		if (!productOne.isEmpty()) {
			Map map = pictureService.uploadPicture(productOne);
			String ftpPath = (String) map.get("url");
			String posPath = ftpPath.substring(20);
			String url = FRONTPATH + posPath;
			shopdetail.setProduct1(url);
		}
		if (!productTwo.isEmpty()) {
			Map map = pictureService.uploadPicture(productTwo);
			String ftpPath = (String) map.get("url");
			String posPath = ftpPath.substring(20);
			String url = FRONTPATH + posPath;
			shopdetail.setProduct2(url);
		}
		if (!productThree.isEmpty()) {
			Map map = pictureService.uploadPicture(productThree);
			String ftpPath = (String) map.get("url");
			String posPath = ftpPath.substring(20);
			String url = FRONTPATH + posPath;
			shopdetail.setProduct3(url);
		}
		if (!productFour.isEmpty()) {
			Map map = pictureService.uploadPicture(productFour);
			String ftpPath = (String) map.get("url");
			String posPath = ftpPath.substring(20);
			String url = FRONTPATH + posPath;
			shopdetail.setProduct4(url);
		}
		if (!productFive.isEmpty()) {
			Map map = pictureService.uploadPicture(productFive);
			String ftpPath = (String) map.get("url");
			String posPath = ftpPath.substring(20);
			String url = FRONTPATH + posPath;
			shopdetail.setProduct5(url);
		}
		if (!productSix.isEmpty()) {
			Map map = pictureService.uploadPicture(productSix);
			String ftpPath = (String) map.get("url");
			String posPath = ftpPath.substring(20);
			String url = FRONTPATH + posPath;
			shopdetail.setProduct6(url);
		}
		shopdetail.setCreateCode(createCode);
		shopdetail.setCreateName(createName);
		sdService.addShopDetail(shopdetail);
		System.out.println("圖檔上傳成功");
		
		return "redirect:query_detail";
	}
           

實際調用非常簡單 , 隻需要一句pictureService.uploadPicture("頁面傳遞過來的檔案名稱")即可實作 , 傳回的是map對象 , 通過map拿到ftp的路徑 , 及經過字元串處理後的檔案名稱 , 拼接成完整的圖檔檔案路徑進行儲存 , 最後檢視上傳後的檔案效果如下 :

上傳圖檔檔案到ftp伺服器

可以看到檔案夾是以日期年月日進行分類 , 管理起來非常友善 , 到此圖檔上傳已經可以實作 , 以我個人為例 , 我ftp資源存放目錄設定的是項目工程目錄 , 當重新釋出的時候會導緻之前上傳的圖檔被清空 , 需要提前備份好ftp上傳的圖檔資源複制到準備重新釋出的項目目錄中 , 再進行釋出 , 以免資源丢失造成不必要的麻煩