天天看點

easyui+springboot+poi實作圖檔,音頻,視訊的上傳(ftp)和回顯(支援IE8)

1:pom.xml.

ftp用戶端:

easyui+springboot+poi實作圖檔,音頻,視訊的上傳(ftp)和回顯(支援IE8)

2:前端代碼

//初始化上傳

function initupload() {

$("#onlineFileName").filebox({

buttonText: ‘選擇檔案’,

prompt: ‘請選擇上傳圖檔(png,gif類型)’,

buttonAlign: ‘right’

});

$("#onlineFileName").textbox(“textbox”).attr(“title”, “僅支援jpg、png檔案格式”);

}

// 上傳

$("#btn-upload").click(function(){

Loading.showLoading("上傳中,請稍後");

var file = $("#onlineFileName").filebox("getValue");

var fileType = file.slice(file.lastIndexOf(".") + 1, file.length);
if (fileType.length == 0) {
    new Dialog({
        mode: 'tips',   //表示是提示,而不是confirm
        content: '請選擇上傳檔案'  //操作失敗提示内容
    });
    Loading.destroyLoading();
    return;
}
if (["png","PNG","gif","GIF"].join("").indexOf(fileType) == -1) {
    new Dialog({
        mode: 'tips',   //表示是提示,而不是confirm
        content: '檔案類型有誤, 請重新上傳檔案'  //操作失敗提示内容
    });
    Loading.destroyLoading();
    return;
}
var province;
Util.ajax.getJson(Util.constants.CONTEXT + "", {}, function (data) {
    if (data.RSP.RSP_CODE == "1") {
        province = data.RSP.DATA[0].provnce;
    } else {
        $.messager.alert('溫馨提示',data.RSP.RSP_DESC);
    }
}, true);
$("#updateMultiMedia").ajaxSubmit({
    url: Util.constants.MULTIMEDIA_IP + "",
    method: "POST",
    async: true,
    headers: {
        "Authorization": Util.getValue()
    },
    data: {
        "province": province
    },
    success: function (serviceResponse) {
        serviceResponse = decodeURI(serviceResponse);
        serviceResponse = JSON.parse(serviceResponse);
        if (serviceResponse.RSP.rspcode == "1") {
            ftpId = serviceResponse.RSP.rspdesc;
            setTimeout(function(){initPhoto(ftpId)},3000);//1000毫秒=1秒後執行test方法
            new Dialog({
                mode: 'tips',   //表示是提示,而不是confirm
                tipsType: 'success',   //提示類型,error表示操作失敗,success表示操作成功,無此字段表示為一般提示
                content: '上傳成功'  //操作失敗提示内容
            });
        } else {
            new Dialog({
                mode: 'tips',   //表示是提示,而不是confirm
                tipsType: 'error',   //提示類型,error表示操作失敗,success表示操作成功,無此字段表示為一般提示
                content: '上傳失敗,請重新上傳!'  //操作失敗提示内容
            });
        }
        $("#onlineFileName").filebox("clear");
        Loading.destroyLoading();
    },
    error: function (data) {
        new Dialog({
            mode: 'tips',   //表示是提示,而不是confirm
            tipsType: 'error',   //提示類型,error表示操作失敗,success表示操作成功,無此字段表示為一般提示
            content: '操作異常!'  //操作失敗提示内容
        });
        $("#onlineFileName").filebox("clear");
        Loading.destroyLoading();
    }
});
3:後端  MultipartFile  對象接受 - control層
@RequestMapping(value = "/upload",method = RequestMethod.POST, produces = "text/plain")
           

public void upload(@RequestParam(“file”) MultipartFile file,@RequestParam(“province”) String province, HttpServletResponse servletResponse) {

KcPersonalCfgResponse response = new KcPersonalCfgResponse();

try {

logger.info(“province:”+province);

response = personalCfgSV.uploadPhotoFile(file,province);

servletResponse.getWriter().write(JSONObject.toJSONString(new KcPersonalCfgServiceResponse().getSuccessResponse(response)));

} catch (Exception e) {

logger.error(“上傳檔案出現異常”, e);

response.setRspdesc(“上傳檔案出現異常!”);

response.setRspcode(WebUtil.EXCEPTION);

}

}

3.1:file 必須和 前端一緻

easyui+springboot+poi實作圖檔,音頻,視訊的上傳(ftp)和回顯(支援IE8)

3.2:後端代碼兼任ie8 ie8不可以接受respone。

4:service層

ftpUtil.java類調用上傳到ftp伺服器:

easyui+springboot+poi實作圖檔,音頻,視訊的上傳(ftp)和回顯(支援IE8)

FtpUtil.java類

package com.unicom.kc.manage.customization.common.ftp;

import org.apache.commons.lang.StringUtils;

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;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import java.io.*;

import java.net.MalformedURLException;

@Component

public class FtpUtil {

private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

private String LOCAL_CHARSET = “GBK”;

//ftp伺服器位址

@Value(" f t p . h o s t n a m e " ) p r i v a t e S t r i n g h o s t n a m e ; / / f t p 服 務 器 端 口 号 默 認 為 21 @ V a l u e ( " {ftp.hostname}") private String hostname; //ftp伺服器端口号預設為21 @Value(" ftp.hostname")privateStringhostname;//ftp伺服器端口号預設為21@Value("{ftp.port}")

private String port;

//ftp登入賬号

@Value(" f t p . u s e r n a m e " ) p r i v a t e S t r i n g u s e r n a m e ; / / f t p 登 錄 密 碼 @ V a l u e ( " {ftp.username}") private String username; //ftp登入密碼 @Value(" ftp.username")privateStringusername;//ftp登入密碼@Value("{ftp.password}")

private String password;

//ftp登入密碼
@Value("${ftp.basePath}")
private String basePath;


/**
 * 初始化ftp伺服器
 */
public FTPClient getFtpClient() {
    FTPClient ftpClient = new FTPClient();
    ftpClient.setControlEncoding("utf-8");
    try {
        ftpClient.setDataTimeout(1000 * 120);
        logger.info("connecting...ftp伺服器:" + hostname + ":" + port);
        ftpClient.connect(hostname, Integer.parseInt(port)); // 連接配接ftp伺服器
        ftpClient.login(username, password); // 登入ftp伺服器
        int replyCode = ftpClient.getReplyCode(); // 是否成功登入伺服器
        if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
                "OPTS UTF8", "ON"))) {      // 開啟伺服器對UTF-8的支援,如果伺服器支援就用UTF-8編碼,否則就使用本地編碼(GBK).
            LOCAL_CHARSET = "UTF-8";
        }
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            logger.error("connect failed...ftp伺服器:" + hostname + ":" + port);
        }
        logger.info("connect successfu...ftp伺服器:" + hostname + ":" + port);
    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return ftpClient;
}


/**
 * 上傳檔案
 *
 * @param pathname    ftp服務儲存位址
 * @param fileName    上傳到ftp的檔案名
 * @param inputStream 輸入檔案流
 * @return
 */
public boolean uploadFileToFtp(String targetDir, String fileName, InputStream inputStream) {
    boolean isSuccess = false;
    String servicePath = String.format("%s%s%s", basePath, "/", targetDir);
    FTPClient ftpClient = getFtpClient();
    try {
        if (ftpClient.isConnected()) {
            logger.info("開始上傳檔案到FTP,檔案名稱:" + fileName);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.makeDirectory(servicePath);
            ftpClient.changeWorkingDirectory(servicePath);
            //設定為被動模式(如上傳檔案夾成功,不能上傳檔案,注釋這行,否則報錯refused:connect  )
            ftpClient.enterLocalPassiveMode();
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            ftpClient.logout();
            isSuccess = true;
            logger.info(fileName + "檔案上傳到FTP成功");
        } else {
            logger.error("FTP連接配接建立失敗");
        }
    } catch (Exception e) {
        logger.error(fileName + "檔案上傳到FTP出現異常");
        logger.error(e.getMessage(), e);
    } finally {
        closeFtpClient(ftpClient);
        closeStream(inputStream);
    }
    return isSuccess;
}

public void closeStream(Closeable closeable) {
    if (null != closeable) {
        try {
            closeable.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

//改變目錄路徑
public boolean changeWorkingDirectory(FTPClient ftpClient, String directory) {
    boolean flag = true;
    try {
        flag = ftpClient.changeWorkingDirectory(directory);
        if (flag) {
            logger.info("進入檔案夾" + directory + " 成功!");

        } else {
            logger.info("進入檔案夾" + directory + " 失敗!開始建立檔案夾");
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return flag;
}

//建立多層目錄檔案,如果有ftp伺服器已存在該檔案,則不建立,如果無,則建立
public boolean CreateDirecroty(FTPClient ftpClient, String remote) throws IOException {
    boolean success = true;

    String directory = remote;
    if (!remote.endsWith(File.separator)) {
        directory = directory + File.separator;
    }
    // 如果遠端目錄不存在,則遞歸建立遠端伺服器目錄
    if (!directory.equalsIgnoreCase(File.separator) && !changeWorkingDirectory(ftpClient, new String(directory))) {
        int start = 0;
        int end = 0;
        if (directory.startsWith(File.separator)) {
            start = 1;
        } else {
            start = 0;
        }
        end = directory.indexOf(File.separator, start);
        String path = "";
        String paths = "";
        while (true) {
            String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
            path = path + File.separator + subDirectory;
            if (!existFile(ftpClient, path)) {
                if (makeDirectory(ftpClient, subDirectory)) {
                    changeWorkingDirectory(ftpClient, subDirectory);
                } else {
                    logger.error("建立目錄[" + subDirectory + "]失敗");
                    changeWorkingDirectory(ftpClient, subDirectory);
                }
            } else {
                changeWorkingDirectory(ftpClient, subDirectory);
            }

            paths = paths + File.separator + subDirectory;
            start = end + 1;
            end = directory.indexOf(File.separator, start);
            // 檢查所有目錄是否建立完畢
            if (end <= start) {
                break;
            }
        }
    }
    return success;
}

//判斷ftp伺服器檔案是否存在
public boolean existFile(FTPClient ftpClient, String path) throws IOException {
    boolean flag = false;
    FTPFile[] ftpFileArr = ftpClient.listFiles(path);
    if (ftpFileArr.length > 0) {
        flag = true;
    }
    return flag;
}

//建立目錄
public boolean makeDirectory(FTPClient ftpClient, String dir) {
    boolean flag = true;
    try {
        flag = ftpClient.makeDirectory(dir);
        if (flag) {
            logger.info("建立檔案夾" + dir + " 成功!");

        } else {
            logger.info("建立檔案夾" + dir + " 失敗!");
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return flag;
}

/**
 * 下載下傳檔案 *
 *
 * @param pathName FTP伺服器檔案目錄 *
 * @param pathName 下載下傳檔案的條件*
 * @return
 */
public boolean downloadFile(FTPClient ftpClient, String pathName, String targetFileName, String localPath) {
    boolean flag = false;
    OutputStream os = null;
    try {
        System.out.println("開始下載下傳檔案");
        //切換FTP目錄
        ftpClient.changeWorkingDirectory(pathName);
        ftpClient.enterLocalPassiveMode();
        FTPFile[] ftpFiles = ftpClient.listFiles();
        for (FTPFile file : ftpFiles) {
            String ftpFileName = file.getName();
            if (targetFileName.equalsIgnoreCase(ftpFileName.substring(0, ftpFileName.indexOf(".")))) {
                File localFile = new File(localPath);
                os = new FileOutputStream(localFile);
                ftpClient.retrieveFile(file.getName(), os);
                os.close();
            }
        }
        ftpClient.logout();
        flag = true;
        logger.info("下載下傳檔案成功");
    } catch (Exception e) {
        logger.error("下載下傳檔案失敗");
        logger.error(e.getMessage(), e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        if (null != os) {
            try {
                os.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return flag;
}

/*下載下傳檔案*/
public InputStream download(String ftpFile, FTPClient ftpClient) throws IOException {
    String servicePath = String.format("%s%s%s", basePath, "/", ftpFile);
    logger.info("【從檔案伺服器擷取檔案流】ftpFile : " + ftpFile);
    if (StringUtils.isBlank(servicePath)) {
        throw new RuntimeException("【參數ftpFile為空】");
    }
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.enterLocalPassiveMode();
    ftpFile = new String(servicePath.getBytes("utf-8"), "iso-8859-1");
    return ftpClient.retrieveFileStream(ftpFile);
}

/**
 * 删除檔案 *
 *
 * @param pathname FTP伺服器儲存目錄 *
 * @param filename 要删除的檔案名稱 *
 * @return
 */
public boolean deleteFile(String pathname, String filename) {
    boolean flag = false;
    FTPClient ftpClient = getFtpClient();
    try {
        logger.info("開始删除檔案");
        if (ftpClient.isConnected()) {
            //切換FTP目錄
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.enterLocalPassiveMode();
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            logger.info("删除檔案成功");
        } else {
            logger.info("删除檔案失敗");

        }
    } catch (Exception e) {
        logger.error("删除檔案失敗");
        logger.error(e.getMessage(), e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return flag;
}

public void closeFtpClient(FTPClient ftpClient) {
    if (ftpClient.isConnected()) {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

public InputStream downloadFile(FTPClient ftpClient, String pathname, String filename) {
    InputStream inputStream = null;
    try {
        System.out.println("開始下載下傳檔案");
        //切換FTP目錄
        ftpClient.changeWorkingDirectory(pathname);
        ftpClient.enterLocalPassiveMode();
        FTPFile[] ftpFiles = ftpClient.listFiles();
        for (FTPFile file : ftpFiles) {
            if (filename.equalsIgnoreCase(file.getName())) {
                inputStream = ftpClient.retrieveFileStream(file.getName());
                break;
            }
        }
        ftpClient.logout();
        logger.info("下載下傳檔案成功");
    } catch (Exception e) {
        logger.error("下載下傳檔案失敗");
        logger.error(e.getMessage(), e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return inputStream;
}
           

// public static void main(String[] args) {

// FtpUtil ftp =new FtpUtil();

// //ftp.uploadFile("/home/ngkm/ftptest", “test_2018_05_23.docx”, “C://test.txt”);

// //ftp.downloadFile("/home/ngkm/ftptest", “test_2018_05_23.docx”, “F://”);

// //ftp.deleteFile("/home/ngkm/ftptest", “test_2018_05_23.docx”);

// System.out.println(“ok”);

// }

}

二:下載下傳(圖檔的回顯)

5:前端代碼

//圖檔回顯

function initPhoto(photoId){

$(’#img_img’).attr(‘src’,Util.constants.CONTEXT + “/kc/manage/cust/msa/showphoto?photoId=”+photoId);

}

将流寫在img标簽的src裡面。

6:後端-control層

@RequestMapping(value = “/showphoto”, method = RequestMethod.GET)

public void showPhoto(@RequestParam(“photoId”) String fileId, HttpServletResponse servletresponse) {

Response response = new Response();

servletresponse.setCharacterEncoding(“UTF-8”);

servletresponse.setContentType(“image/png;charset=UTF-8”);

servletresponse.setHeader(“contentType”, “image/png;charset=UTF-8”);

String ftpFile = String.format("%s%s%s%s", “”, “”, fileId, “.jpg”);

//檔案路徑

FTPClient ftpClient = null;

InputStream inputStream = null;

OutputStream outputStream = null;

try {

ftpClient = ftpUtil.getFtpClient();

inputStream = ftpUtil.download(ftpFile, ftpClient);

outputStream = servletresponse.getOutputStream();

FileCopyUtils.copy(inputStream, outputStream);

} catch (Exception e) {

} finally {

ftpUtil.closeStream(outputStream);

ftpUtil.closeStream(inputStream);

ftpUtil.closeFtpClient(ftpClient);

}

}

7:service層通過 FtpUtil.java類 download方法下載下傳

easyui+springboot+poi實作圖檔,音頻,視訊的上傳(ftp)和回顯(支援IE8)