如何让GUI客户端在java中上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19152256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:32:44  来源:igfitidea点击:

How to make GUI Client to upload file in java

javaswinguser-interfaceserversocket

提问by AR7

Please help me I want to make a GUI application which upload a file from client to server. when I click on browse button then file is copy in bytes form because we travel data in bytes on network but when I click on upload button then file cannot upload.

请帮助我我想制作一个 GUI 应用程序,将文件从客户端上传到服务器。当我单击浏览按钮时,文件以字节形式复制,因为我们在网络上以字节为单位传输数据,但是当我单击上传按钮时,文件无法上传。

import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

class ClientUpload extends JFrame implements ActionListener {

    JFileChooser fc;
    JButton b, b1;
    JTextField tf;
    FileInputStream in;
    Socket s;
    DataOutputStream dout;
    DataInputStream din;
    int i;

    ClientUpload() {
        super("client");
        tf = new JTextField();
        tf.setBounds(20, 50, 190, 30);
        add(tf);

        b = new JButton("Browse");
        b.setBounds(250, 50, 80, 30);
        add(b);
        b.addActionListener(this);
        b1 = new JButton("Upload");
        b1.setBounds(250, 100, 80, 30);
        add(b1);
        b1.addActionListener(this);
        fc = new JFileChooser();
        setLayout(null);
        setSize(400, 300);
        setVisible(true);
        try {
            s = new Socket("localhost", 10);
            dout = new DataOutputStream(s.getOutputStream());
            din = new DataInputStream(s.getInputStream());
            send();
        } catch (Exception e) {
        }
    }

    public void actionPerformed(ActionEvent e) {
        try {
            if (e.getSource() == b) {
                int x = fc.showOpenDialog(null);
                if (x == JFileChooser.APPROVE_OPTION) {
                    copy();
                }
            }
            if (e.getSource() == b1) {
                send();
            }
        } catch (Exception ex) {
        }
    }

    public void copy() throws IOException {
        File f1 = fc.getSelectedFile();
        tf.setText(f1.getAbsolutePath());
        in = new FileInputStream(f1.getAbsolutePath());
        while ((i = in.read()) != -1) {
            System.out.print(i);
        }
    }

    public void send() throws IOException {
        dout.write(i);
        dout.flush();

    }

    public static void main(String... d) {
        new ClientUpload();
    }
}

回答by MadProgrammer

You are basically reading the contents of the file when you select it, discard the contents and then trying to send the last intvalue you read from it to the server. A file my be many, many, many bytes long (think giga bytes), an intins't going to hold that much information (poor int).

选择文件时,您基本上是在读取文件的内容,丢弃内容,然后尝试int将从中读取的最后一个值发送到服务器。一个文件可能有很多,很多,很多字节长(想想千兆字节),int不会保存那么多信息(差int)。

Instead, when the user selects a File, you should maintain a reference to it until you actually need it...

相反,当用户选择 a 时File,您应该维护对它的引用,直到您真正需要它为止......

public void actionPerformed(ActionEvent e) {
    try {
        if (e.getSource() == b) {
            int x = fc.showOpenDialog(null);
            if (x == JFileChooser.APPROVE_OPTION) {
                fileToBeSent = fc.getSelectedFile();
                tf.setText(f1.getAbsolutePath());
                b1.setEnabled(true);
            } else {
                fileToBeSent = null;
                tf.setText(null;);
                b1.setEnabled(false);
            }
        }
        if (e.getSource() == b1) {
            send();
        }
    } catch (Exception ex) {
    }
}

When the user presses the "send" button, you would simply copy the file input stream to the sockets output stream...

当用户按下“发送”按钮时,您只需将文件输入流复制到套接字输出流...

FileInputStream in = null;
try {
    in = new FileInputStream(fileToBeSent);
    byte[] buffer = new byte[1024];
    int bytesIn = -1;
    while ((bytesIn = in.read(buffer)) != -1) {
        dout.write(buffer, 0, bytesIn);
    }
    dout.flush();
} finally {
    try {
        in.close();
    } catch (Exception exp) {
    }
}

That should at least get you one step closer.

这至少应该让你更近一步。

The next problem you are likely to hit is the fact that the UI will stop responding while the transfer is underway.

您可能会遇到的下一个问题是,在传输过程中 UI 将停止响应。

In this case, you should take a look at Concurrency in Swing.

在这种情况下,您应该查看Swing中的Concurrency

Modern UI's need to deal with many different characteristics of client machines, included different fonts, font rendering capabilities, DPI, screen resolutions and lots more. You're putting your self in a very dark and deep hole by using absolute layouts.

现代 UI 需要处理客户端机器的许多不同特征,包括不同的字体、字体渲染能力、DPI、屏幕分辨率等等。通过使用绝对布局,您将自己置身于一个非常黑暗和深邃的洞中。

You should take advantage of the layout manager API which is designed to easy the pressure of these concerns and make you UI more accommodating on different operating environments.

您应该利用布局管理器 API,该 API 旨在减轻这些问题的压力,并使您的 UI 更加适应不同的操作环境。

Take a look at Layout out Components within a Containerfor more deatils

查看Layout out Components within a Container了解更多细节

You may also want to take a closer look at Basic I/Oand All about socketsfor more details...

您可能还想仔细查看Basic I/OAll about sockets以获取更多详细信息...

回答by Mano Chella

You Just Copy and paste this code this will help you ....

您只需复制并粘贴此代码,这将对您有所帮助....

This is Server class

这是服务器类

package newpack;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class SwingControlServer extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SwingControlServer frame = new SwingControlServer();
                    frame.setVisible(false);
                    frame.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    protected static void start() throws IOException {
        // TODO Auto-generated method stub
         System.out.println("Server running...");

            /* Listen on port 5555 */

            ServerSocket server = new ServerSocket(10001);

            /* Accept the sk */

            Socket socket = server.accept();

            System.out.println("Server accepted client");
            InputStream inputStream=socket.getInputStream();
            byte[] readbyte=new byte[(1024*10)*1024];           


            FileOutputStream fileOutputStream=new FileOutputStream("D:/Manoj/hello21.zip");
            int writebyte;
            int count=0;
            while((writebyte=inputStream.read(readbyte))!=-1)
            {
                if(writebyte>0)
                    count+=writebyte;
                fileOutputStream.write(readbyte, 0, writebyte);
            }

            //System.out.println("THE WRITEBYTE VALUE IS "+writebyte+"THE READ BYTE VALUE IS"+count);
            inputStream.close();
            System.out.println("CONNECTION CLOSED");



    }

    /**
     * Create the frame.
     */
    public SwingControlServer() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);


    }


}

This is Client Class

这是客户端类

package newpack;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.StringTokenizer;

import javax.swing.*;

import org.apache.commons.io.FileUtils;



public class SwingControlDemo extends JFrame {

   /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JFrame mainFrame;
   private JPanel controlPanel;
   private String filename;
   private String fname;
   private JProgressBar progressBar;
   private Task task;
   private JButton startButton;
   private JTextArea outputTextArea;
   private JTextField textField;
   private JLabel lblFilename;
   private JButton btnNewButton;
   private JButton btnCancel;
   private JLabel sendinglabel;
   private JLabel starttime;
   private JLabel endtime;
private JLabel sendinglabel1;


   public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showProgressBarDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Large File Upload");
      mainFrame.setSize(492,400);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });
      mainFrame.getContentPane().setLayout(null);

      controlPanel = new JPanel();
      controlPanel.setBounds(0, 0, 491, 355);
      mainFrame.getContentPane().add(controlPanel);
      controlPanel.setLayout(null);
      mainFrame.setVisible(true);  
   }



   private void showProgressBarDemo(){
      controlPanel.setLayout(null);

      textField = new JTextField();
      textField.setBounds(125, 26, 105, 31);
      controlPanel.add(textField);
      textField.setColumns(10);

        sendinglabel=new JLabel("FIle is Sending...");
        sendinglabel.setBounds(10, 128, 168, 30);
        sendinglabel.setVisible(false);
        sendinglabel.setFont(new Font("Times New Roman", Font.PLAIN, 12));
        controlPanel.add(sendinglabel);

        sendinglabel1=new JLabel("FIle is Sending...");
        sendinglabel1.setBounds(51, 200, 250, 30);
        sendinglabel1.setVisible(false);
        sendinglabel1.setFont(new Font("Times New Roman", Font.PLAIN, 12));
        controlPanel.add(sendinglabel1);


        endtime = new JLabel("");
        endtime.setBounds(204, 200, 208, 33);
        endtime.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        controlPanel.add(endtime);


        starttime = new JLabel("");
        starttime.setBounds(273, 141, 208, 33);
        starttime.setFont(new Font("Times New Roman", Font.PLAIN, 14));
        controlPanel.add(starttime);

      ProgressMonitor pc=new ProgressMonitor(SwingControlDemo.this, "Running My Program","", 0,10);


                  progressBar = new JProgressBar(0, 100);
                  progressBar.setBounds(62, 158, 146, 31);
                  progressBar.setValue(0);
                  progressBar.setStringPainted(true);
                  controlPanel.add(progressBar);


                  startButton = new JButton("Send");
                  startButton.setBounds(75, 82, 90, 31);
                  startButton.addActionListener(new ActionListener() {
                  private int i;

                @Override

                  public void actionPerformed(ActionEvent e) {

                    task = new Task();                
                    task.start();

                }});

                        controlPanel.add(startButton);

                              outputTextArea = new JTextArea("",5,20);
                              outputTextArea.setVisible(false);
                              outputTextArea.setBounds(51, 200, 164, 94);
                              controlPanel.add(outputTextArea);

                              lblFilename = new JLabel("FileName");
                              lblFilename.setVisible(true);
                              lblFilename.setBounds(10, 26, 105, 31);
                              lblFilename.setFont(new Font("Times New Roman", Font.PLAIN, 14));
                              controlPanel.add(lblFilename);


                              btnNewButton = new JButton("Browse");
                              btnNewButton.setBounds(258, 26, 105, 31);
                              btnNewButton.addActionListener(new ActionListener() {




                                public void actionPerformed(ActionEvent arg0) {

                                    JFileChooser filedilg=new JFileChooser();
                                    filedilg.showOpenDialog(filedilg);
                                    filename=filedilg.getSelectedFile().getAbsolutePath();
                                    textField.setText(filename);

                                    File file1=new File(filename);
                                    fname = file1.getName();           
                                    System.out.println("THE FILE NAME IS "+fname);
                                }
                              });
                              btnNewButton.setFont(new Font("Times New Roman", Font.PLAIN, 14));
                              controlPanel.add(btnNewButton);

                              btnCancel = new JButton("Cancel");
                              btnCancel.setBounds(182, 82, 90, 31);
                              btnCancel.addActionListener(new ActionListener() {

                                @Override
                                public void actionPerformed(ActionEvent arg0) {
                                    // TODO Auto-generated method stub
                                System.exit(0); 
                                }
                            });
                              controlPanel.add(btnCancel);
                              mainFrame.setVisible(true);  
   }

   private class Task extends Thread {    
      public Task(){   }     

    public void run(){       

        PrintStream ps = null;      
        if(filename!=null)
        {
            DateFormat df=new SimpleDateFormat("HH:mm:ss");
            Calendar c=Calendar.getInstance();
            String starttime=df.format(c.getTime());
            System.out.println("Start time: "+starttime);

         try{
//To get current working directory
            String workingdirectory=System.getProperty("user.dir");
            System.out.println(workingdirectory);
//Create folder name as LogFolder in workingdirectory
            File file1=new File(workingdirectory+"\LogFolder\");

            File f2 = null;         
            //if folder not present we need to create a folder
            if (!file1.exists()) {
                if (file1.mkdir()) {
                    f2=new File(file1, "abc.txt");
                    System.out.println("Directory is created!");
                } else {
                    System.out.println("Failed to create directory!");
                }

            }f2=new File(file1, "abc.txt");
            ps=new PrintStream(f2);

                /* Try to connect to the server on localhost, port 5555 */
            sendinglabel.setVisible(true);
            SwingControlDemo.this.starttime.setText("Start time: "+starttime);

            JOptionPane.showMessageDialog(rootPane, "File is Sending...!!!");






                Socket socket=new Socket("localhost",10001);

                File file=new File(filename);





                double size=(file.length()/(1024*1024));
                //float size1=(float)size;  

                System.out.println("THE FILE SIZE IS "+size);
                //iterate();



                    byte[] mybyte=new byte[(int) file.length()];

                    FileInputStream fileInputStream=new FileInputStream(file);
                    int count;
                    int i=0;
                    OutputStream outputStream=socket.getOutputStream();

                    while((count=fileInputStream.read(mybyte))!=-1)
                    {
                        outputStream.write(mybyte);
                        i+=1;

                        System.out.print("FIle Sent........"+i+"Kilobytes \t");
                        myFun(i, size);



                }
                System.out.println();

                DateFormat df1=new SimpleDateFormat("HH:mm:ss");
                Calendar c1=Calendar.getInstance();
                String endtime=df1.format(c1.getTime());
                System.out.println("End time is : "+endtime);

                JOptionPane.showMessageDialog(rootPane, "File Sent Successfully!!!!\n Start Time is :"+starttime+"\n End Time Is : "+endtime);
                SwingControlDemo.this.endtime.setText(endtime);
                System.out.println("THIS FILE HAS BEEN SENT SUCCESSFULLY!!!");      



                socket.close();
                System.exit(1);



            }

            catch (Exception ex){
                /* Catch any errors */

                JOptionPane.showMessageDialog(rootPane, "Error While Sending File : "+ex.getMessage());
                ex.printStackTrace(ps);

            }
        }
        else
        {
            JOptionPane.showMessageDialog(rootPane, "Please Choose a Valid File");
        }






      }

    private  void myFun(int j,Double mbsize) {
        // TODO Auto-generated method stub

        int per=(int) ((j*100)/mbsize);
        System.out.println("THE INTEGER VALUE IS "+per);
        if(j<mbsize)
        {
            System.out.println("INSIDE IF LOOP");
            progressBar.setValue(per);

        }
        else
        {
            progressBar.setValue(per);

        }
        try {
            Thread.sleep(10);


         } catch (InterruptedException e) {}

      }

    }
   }