1. 程式人生 > >spring boot 實現 前段上傳圖片,後臺將圖片轉存的前臺伺服器(FTPClient)

spring boot 實現 前段上傳圖片,後臺將圖片轉存的前臺伺服器(FTPClient)

最近做一個增加產品的介面,需要上傳圖片到前臺路徑下就通過前臺FTPClient實現後臺將檔案轉存到前臺伺服器路徑下,

public String hostname = "hxxxxxxxxxxx";
//ftp伺服器埠號預設為21
public Integer port = 21 ;
//ftp登入賬號
public String username = "xxxxxxx";
//ftp登入密碼
public String password = "xxxxxxx";

public FTPClient ftpClient = null;

/**
 * 初始化ftp伺服器
 */
public void initFtpClient() {
    ftpClient = new FTPClient();
    ftpClient.setControlEncoding("utf-8");
    try {
        System.out.println("connecting...ftp伺服器:"+this.hostname+":"+this.port);
        ftpClient.connect(hostname, port); //連線ftp伺服器
        ftpClient.login(username, password); //登入ftp伺服器
        int replyCode = ftpClient.getReplyCode(); //是否成功登入伺服器
        if(!FTPReply.isPositiveCompletion(replyCode)){
            System.out.println("connect failed...ftp伺服器:"+this.hostname+":"+this.port);
        }
        System.out.println("connect successfu...ftp伺服器:"+this.hostname+":"+this.port);
    }catch (MalformedURLException e) {
        e.printStackTrace();
    }catch (IOException e) {
        e.printStackTrace();
    }
}
public boolean uploadFile( String pathname, String fileName,InputStream inputStream){
    boolean flag = false;
    try{
        System.out.println("開始上傳檔案");
        initFtpClient();
        ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
        CreateDirecroty(pathname);
        ftpClient.makeDirectory(pathname);
        ftpClient.changeWorkingDirectory(pathname);
        ftpClient.storeFile(fileName, inputStream);
        inputStream.close();
        ftpClient.logout();
        flag = true;
        System.out.println("上傳檔案成功");
    }catch (Exception e) {
        System.out.println("上傳檔案失敗");
        e.printStackTrace();
    }finally{
        if(ftpClient.isConnected()){
            try{
                ftpClient.disconnect();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(null != inputStream){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}

controlls層實現:

@ApiOperation(value = "獲取產品列表", notes = "獲取產品列表")
@GetMapping("/selectProduct")
public List<Product> selectProduct()
{
   return productService.selectInfo();
}
@ApiOperation(value = "新增產品", notes = "新增產品")
@PostMapping("/InsertProduct")
public String InsertProduct(@RequestParam MultipartFile file, @RequestParam String ProductName, @RequestParam String ProductInfo)
{
    try {
        File dir = new File("upload/");
        if(!dir.exists()) {
            dir.mkdir();
        }
        String path = "upload/"+ file.getOriginalFilename();
       // File tempFile = null;tempFile =  new File(path);
        //file.transferTo(tempFile);
        FileUtil.uploadFile(file.getBytes(), "upload/", file.getOriginalFilename());
        String ArmfilePath = "/htdocs/images";
        FTPUtil obj = new FTPUtil();
        obj.uploadFile(ArmfilePath,file.getOriginalFilename(),new FileInputStream(path));
        File deletefile = new File(path);
        deletefile.delete();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    Product obj = new Product();
    obj.setName(ProductName);
    obj.setInfo(ProductInfo);
    obj.setFilepath("images/" + file.getOriginalFilename());
    productService.insertInfo(obj);
    return "OK";
}

先上傳到臨時檔案,再將檔案上傳到FTP路徑下。

public class FileUtil {
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}