java中把base64格式的字符串轉化為圖片並保存到ftp服務器上


saveImage()方法

// 分別獲取當前日期 與小時做文件夾
SimpleDateFormat formapath = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat formahhpath = new SimpleDateFormat("HH");
// 分別獲取當前日期 與小時做文件夾
String yyMMdd = formapath.format(new Date());
String hours = formahhpath.format(new Date());
// 文件名
String fileName = "123456.jpg";
// 文件夾路徑
String filePath = yyMMdd + "/" + hours;
// 上傳的base64字符串
String imgbyte = json.getString("IMGBYTE");          
imgbyte = imgbyte.replace(" ", "+");
byte[] inputByte = Base64.decodeBase64(imgbyte);
InputStream insComing = new ByteArrayInputStream(inputByte);
boolean isSuccess = upLoadFile("172.60.6.51", 21, "ftpuser", "ftpuser1", filePath, fileName, insComing);
if (!isSuccess)
    throw new ServiceException("", "保存進FTP服務器失敗");

upLoadFile方法

private boolean upLoadFile(String IP, int port, String userName, String password, String pathName, String fileName, InputStream in) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(IP, port);// 連接FTP服務器
        // 如果采用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
        ftp.login(userName, password);// 登錄
        ftp.setDataTimeout(30000);
        ftp.setBufferSize(1024);
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new IOException("FTP登錄失敗" + IP + "/" + port + "/" + userName + "/" + password);
        }
        for (String str : pathName.split("/")) {
            ftp.makeDirectory(str);
            ftp.changeWorkingDirectory(str);
        }
        boolean tag = ftp.storeFile(fileName, in);
        if (!tag) {
            throw new Exception("保存到FTP失敗");
        }
        success = true;
    } catch (Exception e) {
        try {
            throw new Exception("圖片上傳FTP失敗" + e.getMessage());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    } finally {
        try {
            in.close();// 在這里關閉,保證一定要關閉
            ftp.logout();// 在這里登出,保證一定要登出
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

 附上base64與圖片轉換的在線轉換地址:http://tool.chinaz.com/tools/imgtobase


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM