0

长期搜索者,第一次询问堆栈溢出问题。我似乎总是能够通过搜索找到我的答案,除了这次:)

我有点像 Java 编程的初学者。虽然我认为使用 apache commons ftp 的小程序是在我的网站上实现 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 初学者。我可能没有使用正确的方法,欢迎提出建议。

谢谢!麦克风

4

1 回答 1

0

我想通了,我需要将 javascript 调用的方法包装在 AccessController.doPrivileged 中,如下所示:

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;
        }
    });
}
于 2013-01-20T14:35:56.430 回答