簡體   English   中英

在HTML按鈕上上傳Apache Commons FTP Applet

[英]Apache Commons FTP Applet upload on html button

長期的搜索者,第一次問堆棧溢出問題。 除了這次以外,我似乎總是能夠通過搜索找到答案:)

我有些是Java編程的初學者。 盡管我認為使用apache commons ftp的applet是在我的網站上實現FTP文件上傳解決方案的最佳解決方案。

當我將所有代碼都放在init()方法中時,便能夠傳輸文件。

雖然當我將代碼移動到我在javascript中調用的另一種方法時,在打印工作目錄(PWD)后它失敗了。

此代碼有效

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

import java.io.IOException;
import javax.swing.JApplet;
import javax.swing.*;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.io.Util;
import org.apache.commons.net.io.CopyStreamAdapter;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;
/**
 *
 * @author Mike
 */
public class FTPMain extends JApplet {
    int userId;
    private File[] files;
    final JPanel myPanel = new JPanel();
    final JLabel lblStatus = new JLabel();    
    final JProgressBar myProgressBar = new JProgressBar();

    //Called when this applet is loaded into the browser.
    public void init() {

        JButton btnSelectFiles = new JButton("Select Files");
        JButton btnUpload = new JButton("Upload Files");

        myPanel.add(btnSelectFiles);
        myPanel.add(btnUpload);
        myPanel.add(lblStatus);
        myPanel.add(myProgressBar);
        myPanel.setBackground(Color.white);

        btnSelectFiles.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                 final JFileChooser fc = new JFileChooser();
                 fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                 fc.setMultiSelectionEnabled(true);
                 int returnVal = fc.showOpenDialog(myPanel);
                 if(returnVal == JFileChooser.APPROVE_OPTION) {
                     files = fc.getSelectedFiles(); 
                     //for(int i = 0; i < files.length; i++) {
                     lblStatus.setText("File count:  " + files.length);
                     //}
                 } else {
                    lblStatus.setText("Open command cancelled by user.");
                 }
             }
        });

        btnUpload.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                lblStatus.setText("Uploading Files...");

                final FTPClient ftpclient = new FTPClient();
                //ftpclient.setControlKeepAliveTimeout(300);
                File myFile;
                try {

                    FTPUtils.ftpConnect(ftpclient, "myhost", "myusername", "mypassword");
                    //ftpclient.enterLocalPassiveMode();
                    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

                    for(int i = 0; i < files.length; i++) {
                        String to = "/path/to/files/queue";
                        ftpclient.changeWorkingDirectory(to);
                        ftpclient.printWorkingDirectory();
                        myFile = new File(files[i].getAbsolutePath());
                        final String remoteFile = myFile.getName();
                        final InputStream inputStream = new FileInputStream(myFile);
                        final OutputStream outputStream = ftpclient.storeFileStream(remoteFile);

                        //byte[] bytesIn = new byte[4096];
                        //int read = 0;
                        int streamSize = (int)files[i].getTotalSpace();
                        Util.copyStream(inputStream, outputStream, 4096, streamSize, myListener);

                        /*while((read = inputStream.read(bytesIn)) != -1) {
                            outputStream.write(bytesIn, 0, read);
                        }*/

                        inputStream.close();
                        outputStream.close();
                        boolean completed = ftpclient.completePendingCommand();

                        if(completed) {
                            lblStatus.setText((i+1) + " files have been uploaded successfully.");
                        }
                    }
                } catch (IOException ex) {
                    // TODO Auto-generated catch block
                    lblStatus.setText(ex.getMessage());
                    //ex.printStackTrace();
                }
            }
        });

        getContentPane().add(myPanel);
    }

    public CopyStreamListener myListener = new CopyStreamListener(){
        //private long megsTotal = 0;
        public void bytesTransferred(CopyStreamEvent event) {
            bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize());
        }

        public void bytesTransferred(long totalBytesTransferred,
                int bytesTransferred, long streamSize) {

            final int percent = (bytesTransferred / (int)streamSize) * 100;
            //myProgressBar.setString("Processing " + percent + "%");
            //myProgressBar.setValue(percent);
            lblStatus.setText("Total: "+percent);
            /*long megs = totalBytesTransferred / 1000000;
            for (long l = megsTotal; l < megs; l++) {
                System.err.print("#");
            }
            megsTotal = megs;
            myLabel.setText("Total: " + megsTotal);
            myProgressBar.setValue((int)megsTotal);*/
        }
    };

    //private static CopyStreamListener createListener(){
    //    return 
    //}

    public void startFTPUpload(String strUserInfo) {

        //myLabel.setText("UserId " + userId + " is now set.");
    }
}

盡管當我將文件傳輸代碼(在btnUpload Action Listener中)移動到startFTPUpload方法,並通過javascript運行它時,它在PWD行之后失敗了,沒有錯誤。

/* javascript code */
$("#btnUpload").click(function() {
    var val = $(this).val();
    var myApp = document.applets["FTPUpload"];
    if(myApp) { 
        //alert("found app");
        myApp.startFTPUpload(val);
    }                     
});
/* ----------------- */

public void startFTPUpload(String strUserInfo) {
        lblStatus.setText("Uploading Files...");

        final FTPClient ftpclient = new FTPClient();
        //ftpclient.setControlKeepAliveTimeout(300);
        File myFile;
        try {

            FTPUtils.ftpConnect(ftpclient, "myhost", "myusername", "mypassword");
            //ftpclient.enterLocalPassiveMode();
            ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

            for(int i = 0; i < files.length; i++) {
                String to = "/path/to/files/queue";
                ftpclient.changeWorkingDirectory(to);
                ftpclient.printWorkingDirectory();
                myFile = new File(files[i].getAbsolutePath());
                final String remoteFile = myFile.getName();
                final InputStream inputStream = new FileInputStream(myFile);
                final OutputStream outputStream = ftpclient.storeFileStream(remoteFile);

                //byte[] bytesIn = new byte[4096];
                //int read = 0;
                int streamSize = (int)files[i].getTotalSpace();
                Util.copyStream(inputStream, outputStream, 4096, streamSize, myListener);

                /*while((read = inputStream.read(bytesIn)) != -1) {
                    outputStream.write(bytesIn, 0, read);
                }*/

                inputStream.close();
                outputStream.close();
                boolean completed = ftpclient.completePendingCommand();

                if(completed) {
                    lblStatus.setText((i+1) + " files have been uploaded successfully.");
                }
            }
        } catch (IOException ex) {
            // TODO Auto-generated catch block
            lblStatus.setText(ex.getMessage());
            //ex.printStackTrace();
        }
        //myLabel.setText("UserId " + userId + " is now set.");
    }

非常感謝您的幫助,請記住我是Java初學者。 我可能沒有使用正確的方法,不願意提出建議。

謝謝! 麥克風

我想通了,我需要在AccessController.doPrivileged中包裝由javascript調用的方法,如下所示:

public void startFTPUpload(String strUserInfo) {
    AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            try {
                final FTPClient ftpclient = new FTPClient();

                File myFile;
                try {

                    FTPUtils.ftpConnect(ftpclient, "host", "username", "password");
                    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

                    for(int i = 0; i < files.length; i++) {
                        String to = "/tekmtn.com/sites/testingsite.com/files/queue";
                        ftpclient.changeWorkingDirectory(to);
                        ftpclient.printWorkingDirectory();
                        myFile = new File(files[i].getAbsolutePath());
                        final String remoteFile = myFile.getName();

                        FTPUtils.uploadFile(ftpclient, files[i].getAbsolutePath(), remoteFile);
                        boolean completed = ftpclient.completePendingCommand();
                        if(completed) {
                            lblStatus.setText((i+1) + " files have been uploaded successfully.");
                        }
                    }
                } catch (IOException ex) {
                    // TODO Auto-generated catch block
                    lblStatus.setText(ex.getMessage());
                    //ex.printStackTrace();
                }
                //myLabel.setText("UserId " + userId + " is now set.");
            } catch (Exception e) {
                lblStatus.setText(e.getMessage());
            }
            return Boolean.TRUE;
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM