真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

JAVAFTP上傳文件

下面展示通過http 方式上傳文件到服務(wù)器

海州網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)公司自2013年創(chuàng)立以來到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司

/**

  • 文件上傳接口
  • @param request【module】【filename】
  • @param response
  • @throws IOException */
    @RequestMapping("/upload")
    br/>*/
    @RequestMapping("/upload")
    params) throws IOException{
    String module=params.get("module");//請求模塊,根據(jù)模塊請求的文件放到不通目錄
    log.info("upload method param:"+module);
    if (!validPublicModule(module)) {
    ReponseUtils.renderJsonp(request, response, RespObj.failedObj("上傳目錄不正確"));
    return;
    }
    //打開連接FTP
    FtpUtils ftp=FtpUtils.getInstance();
    InputStream input = null;
    if(filename != null){
    log.info("ftp opern sucess:");
    String newFileName=newfileName(filename);
    input=filename.getInputStream();
    String ftppath=getDirPath(module) ;
    Boolean isfalg=ftp.uploadFile(input, newFileName, ftppath);
    if(!isfalg){
    ReponseUtils.renderJsonp(request, response, RespObj.failedObj("文件上傳異常"));
    return;
    }
    RespObj obj = RespObj.successObj();
    String url=ftppath+File.separator+newFileName;
    log.info("ftp url:"+url);
    obj.setData(url);
    obj.setErrorMsg("sucess");
    ReponseUtils.renderJsonp(request, response, obj);
    }
    }

        FTP 工具類:
    
        package com.ejauto.core.ftp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

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.apache.log4j.Logger;

import com.ejauto.core.utils.Constants;

public class FtpUtils {

Logger log = Logger.getLogger(FtpUtils.class);

private FTPClient ftpClient = null;
private String server;
private int port;
private String userName;
private String userPassword;

private FtpUtils(String server,int port,String userName,String userPassword) {
    this.server = server;
    this.port = port;
    this.userName = userName;
    this.userPassword = userPassword;
}

/**
 * 連接服務(wù)器
 * @return 連接成功與否 true:成功, false:失敗
 */
public boolean open() {

    if (ftpClient != null && ftpClient.isConnected()) {
        return true;
    }
    try {
        ftpClient = new FTPClient();
        // 連接
        ftpClient.connect(this.server, this.port);
        ftpClient.login(this.userName, this.userPassword);
        setFtpClient(ftpClient);
        // 檢測連接是否成功
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            this.close();
            System.err.println("FTP server refused connection.");
            //System.exit(1);
        }
        log.info("open FTP success:" + this.server + ";port:" + this.port + ";name:" + this.userName
                + ";pwd:" + this.userPassword);
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 設(shè)置上傳模式.binally  or ascii
        return true;
    } catch (Exception ex) {
        this.close();
        ex.printStackTrace();
        return false;
    }
}

/**
 * 切換到父目錄
 * @return 切換結(jié)果 true:成功, false:失敗
 */
@SuppressWarnings("unused")
private boolean changeToParentDir() {
    try {
        return ftpClient.changeToParentDirectory();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 改變當(dāng)前目錄到指定目錄
 * @param dir 目的目錄
 * @return 切換結(jié)果 true:成功,false:失敗
 */
@SuppressWarnings("unused")
private boolean cd(String dir) {
    try {
        return ftpClient.changeWorkingDirectory(dir);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 獲取目錄下所有的文件名稱
 * 
 * @param filePath 指定的目錄
 * @return 文件列表,或者null
 */
@SuppressWarnings("unused")
private FTPFile[] getFileList(String filePath) {
    try {
        return ftpClient.listFiles(filePath);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * 層層切換工作目錄
 * @param ftpPath 目的目錄
 * @return 切換結(jié)果
 */
public boolean changeDir(String ftpPath) {
    if (!ftpClient.isConnected()) {
        return false;
    }
    try {
        // 將路徑中的斜杠統(tǒng)一
        char[] chars = ftpPath.toCharArray();
        StringBuffer sbStr = new StringBuffer(256);
        for (int i = 0; i < chars.length; i++) {
            if ('\\' == chars[i]) {
                sbStr.append('/');
            } else {
                sbStr.append(chars[i]);
            }
        }
        ftpPath = sbStr.toString();
        if (ftpPath.indexOf('/') == -1) {
            // 只有一層目錄
            ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
        } else {
            // 多層目錄循環(huán)創(chuàng)建
            String[] paths = ftpPath.split("/");
            for (int i = 0; i < paths.length; i++) {
                ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
            }
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 循環(huán)創(chuàng)建目錄,并且創(chuàng)建完目錄后,設(shè)置工作目錄為當(dāng)前創(chuàng)建的目錄下
 * @param ftpPath 需要創(chuàng)建的目錄
 * @return
 */
public boolean mkDir(String ftpPath) {
    if (!ftpClient.isConnected()) {
        return false;
    }
    try {
        // 將路徑中的斜杠統(tǒng)一
        char[] chars = ftpPath.toCharArray();
        StringBuffer sbStr = new StringBuffer(256);
        for (int i = 0; i < chars.length; i++) {
            if ('\\' == chars[i]) {
                sbStr.append('/');
            } else {
                sbStr.append(chars[i]);
            }
        }
        ftpPath = sbStr.toString();

        if (ftpPath.indexOf('/') == -1) {
            // 只有一層目錄
            ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
            ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
        } else {
            // 多層目錄循環(huán)創(chuàng)建
            String[] paths = ftpPath.split("/");
            for (int i = 0; i < paths.length; i++) {
                ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
                ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
            }
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 上傳文件到FTP服務(wù)器
 * @param localDirectoryAndFileName 本地文件目錄和文件名
 * @param ftpFileName 上傳到服務(wù)器的文件名
 * @param ftpDirectory FTP目錄如:/path2/pathb2/,如果目錄不存在會自動創(chuàng)建目錄
 * @return
 */
public boolean uploadFile(InputStream fis, String ftpFileName, String ftpDirectory) {
    if (!ftpClient.isConnected()) {
        return false;
    }
    boolean flag = false;
    if (ftpClient != null) {
        //File srcFile = new File(localDirectoryAndFileName);
        //InputStream fis = null;
        try {
            //fis = new InputStream(srcFile);
            // 創(chuàng)建目錄
            this.mkDir(ftpDirectory);
            ftpClient.setBufferSize(100000);
            ftpClient.setControlEncoding("UTF-8");
            // 設(shè)置文件類型(二進(jìn)制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            // 上傳
            log.error("ftpClient.storeFile:");
            flag = ftpClient.storeFile(new String(ftpFileName.getBytes("UTF-8"),"iso-8859-1"), fis);
        } catch (Exception e) {
            this.close();
            e.printStackTrace();
            log.error("Exception:"+e.getMessage());
            return false;
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return flag;
}

/**
 * 從FTP服務(wù)器上下載文件
 * @param ftpDirectoryAndFileName ftp服務(wù)器文件路徑,以/dir形式開始
 * @param localDirectoryAndFileName 保存到本地的目錄
 * @return
 */
public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) {
    if (!ftpClient.isConnected()) {
        return false;
    }
    ftpClient.enterLocalPassiveMode(); // Use passive mode as default
    try {
        // 將路徑中的斜杠統(tǒng)一
        char[] chars = ftpDirectoryAndFileName.toCharArray();
        StringBuffer sbStr = new StringBuffer(256);
        for (int i = 0; i < chars.length; i++) {
            if ('\\' == chars[i]) {
                sbStr.append('/');
            } else {
                sbStr.append(chars[i]);
            }
        }
        ftpDirectoryAndFileName = sbStr.toString();
        String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/"));
        String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1);
        this.changeDir(filePath);
        ftpClient.retrieveFile(new String(fileName.getBytes(), "iso-8859-1"),
                new FileOutputStream(localDirectoryAndFileName)); // download
        // file
        //System.out.println(ftpClient.getReplyString()); // check result
        //System.out.println("從ftp服務(wù)器上下載文件:" + ftpDirectoryAndFileName + ", 保存到:" + localDirectoryAndFileName);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 返回FTP目錄下的文件列表
 * @param pathName
 * @return
 */
public String[] getFileNameList(String pathName) {
    try {
        return ftpClient.listNames(pathName);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * 刪除FTP上的文件
 * @param ftpDirAndFileName 路徑開頭不能加/,比如應(yīng)該是test/filename1
 * @return
 */
public boolean deleteFile(String ftpDirAndFileName) {
    if (!ftpClient.isConnected()) {
        return false;
    }
    try {
        return ftpClient.deleteFile(ftpDirAndFileName);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 刪除FTP目錄
 * @param ftpDirectory
 * @return
 */
public boolean deleteDirectory(String ftpDirectory) {
    if (!ftpClient.isConnected()) {
        return false;
    }
    try {
        return ftpClient.removeDirectory(ftpDirectory);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 關(guān)閉鏈接
 */
public void close() {
    try {
        if (ftpClient != null && ftpClient.isConnected()) {
            ftpClient.disconnect();
        }
        System.out.println("成功關(guān)閉連接,服務(wù)器ip:" + this.server + ", 端口:" + this.port);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public FTPClient getFtpClient() {
    return ftpClient;
}

public void setFtpClient(FTPClient ftpClient) {
    this.ftpClient = ftpClient;
}

public void download(HttpServletResponse response,String ftpDirectoryAndFileName){

    if (!ftpClient.isConnected()) {
        return ;
    }
    ftpClient.enterLocalPassiveMode(); // Use passive mode as default
    try {
        // 將路徑中的斜杠統(tǒng)一
        char[] chars = ftpDirectoryAndFileName.toCharArray();
        StringBuffer sbStr = new StringBuffer(256);
        for (int i = 0; i < chars.length; i++) {
            if ('\\' == chars[i]) {
                sbStr.append('/');
            } else {
                sbStr.append(chars[i]);
            }
        }
        ftpDirectoryAndFileName = sbStr.toString();
        String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/"));

        String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1);
        this.changeDir(filePath);
        InputStream inputStream = ftpClient.retrieveFileStream(new String(fileName.getBytes(), "iso-8859-1"));

        ServletOutputStream outputStream = null;
        try {
            response.setHeader("content-disposition", "attachment;filename="+fileName);
            //通知瀏覽器下載文件類型,解決部分瀏覽器下載APK為.htm格式
            response.setContentType("application/octet-stream");

            outputStream = response.getOutputStream();
            byte[] buffer = new byte[8192];
            int len = inputStream.read(buffer);
            while (len != -1) {
                outputStream.write(buffer, 0, len);
                len = inputStream.read(buffer);
            }
            outputStream = response.getOutputStream();

            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
            byte[] buff = new byte[100];  
            int rc = 0;  
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {  
                swapStream.write(buff, 0, rc);  
            }  
            byte[] in2b = swapStream.toByteArray();  
            outputStream.write(in2b);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
                if(outputStream!=null){
                    outputStream.flush();
                    outputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }catch(Exception e){
        log.info(e.getMessage());
        e.printStackTrace();
    }
}

public void downloadImg(HttpServletResponse response,String ftpDirectoryAndFileName){

    if (!ftpClient.isConnected()) {
        return ;
    }
    ftpClient.enterLocalPassiveMode(); // Use passive mode as default
    try {
        // 將路徑中的斜杠統(tǒng)一
        char[] chars = ftpDirectoryAndFileName.toCharArray();
        StringBuffer sbStr = new StringBuffer(256);
        for (int i = 0; i < chars.length; i++) {
            if ('\\' == chars[i]) {
                sbStr.append('/');
            } else {
                sbStr.append(chars[i]);
            }
        }
        ftpDirectoryAndFileName = sbStr.toString();
        String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/"));

        String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1);
        this.changeDir(filePath);
        InputStream inputStream = ftpClient.retrieveFileStream(new String(fileName.getBytes(), "iso-8859-1"));

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[8192];
            int len = inputStream.read(buffer);
            while (len != -1) {
                outputStream.write(buffer, 0, len);
                len = inputStream.read(buffer);
            }
            outputStream = response.getOutputStream();

            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
            byte[] buff = new byte[100];  
            int rc = 0;  
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {  
                swapStream.write(buff, 0, rc);  
            }  
            byte[] in2b = swapStream.toByteArray();  
            outputStream.write(in2b);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
                if(outputStream!=null){
                    outputStream.flush();
                    outputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }catch(Exception e){
        log.info(e.getMessage());
        e.printStackTrace();
    }
}

public boolean upload(InputStream fis, String ftpDirectory){

    String ftpFileName = ftpDirectory.substring(ftpDirectory.indexOf("/"));

    return uploadFile(fis, ftpFileName, ftpDirectory);

}

public static FtpUtils getInstance(){

    String host = Constants.FTP_HOST;
    int port = Integer.valueOf(Constants.FTP_PORT).intValue();
    String user = Constants.FTP_USERNAME;
    String pwd = Constants.FTP_PWD;

    FtpUtils f = new FtpUtils(host, port, user, pwd);

    if(f.open()){
        return f;
    }

    return null;
}
public static void main(String[] args) {
    FileInputStream input = null;
    FtpUtils f=FtpUtils.getInstance();

}

public String getFilePath(HttpServletResponse response,String fileName) throws IOException{

 if (!ftpClient.isConnected()) {
     return "";
 }
 ftpClient.enterLocalPassiveMode(); // Use passive mode as default
 ftpClient.getPassiveLocalIPAddress();
 System.out.println("getPassiveLocalIPAddress:"+ftpClient.getLocalAddress());
 String url="ftp://"+ftpClient.getLocalAddress()+File.separator+fileName;//拼接ftp 路徑
 return url;
}

}


網(wǎng)站標(biāo)題:JAVAFTP上傳文件
轉(zhuǎn)載來于:http://weahome.cn/article/jsgpec.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部