当前位置: 首页 > 面试题库 >

如何使用Apache HttpClient 4获取文件上传的进度条?

白泽语
2023-03-14
问题内容

对于使用Apache的HTTP客户端(org.apache.http.client)上传文件,我具有以下代码:

  public static void main(String[] args) throws Exception
  {
    String fileName = "test.avi";
    File file = new File(fileName);

    String serverResponse = null;
    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);
    HttpPut put = new HttpPut("http://localhost:8080/" + fileName);

    FileEntity fileEntity = new FileEntity(file, "binary/octet-stream");
    put.setEntity(fileEntity);

    HttpResponse response = client.execute(put);
    HttpEntity entity = response.getEntity();
    if (entity != null)
    {
      serverResponse = EntityUtils.toString(entity);
      System.out.println(serverResponse);
    }
  }

效果很好,但是现在我想要一个进度条来显示文件上传的进度。如何做到这一点?我在使用Java的文件上传(带有进度栏)中找到了一个代码段,但是它是为Apache HTTP Client3(org.apache.commons.httpclient)设计的,而RequestEntity类在Apache HTTP Client 4中不存在。

也许你们中的某人有办法?


问题答案:

大家好!

我自己解决了这个问题,并给出了一个简单的例子。
如有任何疑问,请随时提问。

开始了!

ApplicationView.java

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpVersion;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpParams;
    import org.apache.http.params.HttpProtocolParams;
    import org.apache.http.util.EntityUtils;

    public class ApplicationView implements ActionListener
    {

      File file = new File("C:/Temp/my-upload.avi");
      JProgressBar progressBar = null;

      public ApplicationView()
      {
        super();
      }

      public void createView()
      {
        JFrame frame = new JFrame("File Upload with progress bar - Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0, 0, 300, 200);
        frame.setVisible(true);

        progressBar = new JProgressBar(0, 100);
        progressBar.setBounds(20, 20, 200, 30);
        progressBar.setStringPainted(true);
        progressBar.setVisible(true);

        JButton button = new JButton("upload");
        button.setBounds(progressBar.getX(),
                progressBar.getY() + progressBar.getHeight() + 20,
                100,
                40);
        button.addActionListener(this);

        JPanel panel = (JPanel) frame.getContentPane();
        panel.setLayout(null);
        panel.add(progressBar);
        panel.add(button);
        panel.setVisible(true);
      }

      public void actionPerformed(ActionEvent e)
      {
        try
        {
          sendFile(this.file, this.progressBar);
        }
        catch (Exception ex)
        {
          System.out.println(ex.getLocalizedMessage());
        }
      }

      private void sendFile(File file, JProgressBar progressBar) throws Exception
      {
        String serverResponse = null;
        HttpParams params = new BasicHttpParams();
        params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpClient client = new DefaultHttpClient(params);
        HttpPut put = new HttpPut("http://localhost:8080/" + file.getName());

        ProgressBarListener listener = new ProgressBarListener(progressBar);
        FileEntityWithProgressBar fileEntity = new FileEntityWithProgressBar(file, "binary/octet-stream", listener);
        put.setEntity(fileEntity);

        HttpResponse response = client.execute(put);
        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
          serverResponse = EntityUtils.toString(entity);
          System.out.println(serverResponse);
        }
      }
    }

FileEntityWithProgressBar.java

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import org.apache.http.entity.AbstractHttpEntity;

    /**
     * File entity which supports a progress bar.<br/>
     * Based on "org.apache.http.entity.FileEntity".
     * @author Benny Neugebauer (www.bennyn.de)
     */
    public class FileEntityWithProgressBar extends AbstractHttpEntity implements Cloneable
    {

      protected final File file;
      private final ProgressBarListener listener;
      private long transferredBytes;

      public FileEntityWithProgressBar(final File file, final String contentType, ProgressBarListener listener)
      {
        super();
        if (file == null)
        {
          throw new IllegalArgumentException("File may not be null");
        }
        this.file = file;
        this.listener = listener;
        this.transferredBytes = 0;
        setContentType(contentType);
      }

      public boolean isRepeatable()
      {
        return true;
      }

      public long getContentLength()
      {
        return this.file.length();
      }

      public InputStream getContent() throws IOException
      {
        return new FileInputStream(this.file);
      }

      public void writeTo(final OutputStream outstream) throws IOException
      {
        if (outstream == null)
        {
          throw new IllegalArgumentException("Output stream may not be null");
        }
        InputStream instream = new FileInputStream(this.file);
        try
        {
          byte[] tmp = new byte[4096];
          int l;
          while ((l = instream.read(tmp)) != -1)
          {
            outstream.write(tmp, 0, l);
            this.transferredBytes += l;
            this.listener.updateTransferred(this.transferredBytes);
          }
          outstream.flush();
        }
        finally
        {
          instream.close();
        }
      }

      public boolean isStreaming()
      {
        return false;
      }

      @Override
      public Object clone() throws CloneNotSupportedException
      {
        return super.clone();
      }
    }

ProgressBarListener.java

    import javax.swing.JProgressBar;

    public class ProgressBarListener
    {

      private int transferedMegaBytes = 0;
      private JProgressBar progressBar = null;

      public ProgressBarListener()
      {
        super();
      }

      public ProgressBarListener(JProgressBar progressBar)
      {
        this();
        this.progressBar = progressBar;
      }

      public void updateTransferred(long transferedBytes)
      {
        transferedMegaBytes = (int) (transferedBytes / 1048576);
        this.progressBar.setValue(transferedMegaBytes);
        this.progressBar.paint(progressBar.getGraphics());
        System.out.println("Transferred: " + transferedMegaBytes + " Megabytes.");
      }
    }

编码愉快!



 类似资料:
  • 我试图得到一个1分钟的视频上传到firebase桶存储使用管理SDK的进度。我见过很多关于使用firebase.storage().ref.child....但我无法做到这一点与管理sdk,因为他们没有相同的功能。这是我的文件上传: 这个方法现在还可以,但唯一的问题是用户不能看到他们的1或2分钟视频上传的位置。目前,它只是一个活动指示器,用户只是坐着等待,没有任何通知。如果有帮助的话,我会在前端使

  • 我正在使用@googlecloud/storage npm包从NodeJS上传文件。正在将文件成功上传到google云存储桶。参考:https://github.com/GoogleCloudPlatform/google-cloud-node/tree/storage-1.1.0#cloud-存储ga 但对于较大的文件(大小) 我提交AJAX请求与文件作为格式数据到REST API(使用Node

  • 我在下面有这样的代码 我的目标是使用API上传图像,并获得其上传进度。将图像转换为base 64并插入到

  • 我正在制作一个应用程序,让用户使用AWS S3将他们的视频上传到我们的终端。我使用服务器生成签名url并将其返回给客户端(Web浏览器),然后客户端使用该url上传到我们的后端。它工作得很好,但我有一个小问题,我们无法跟踪从浏览器开始的文件上传的进度。 那么,有什么方法可以让我们从服务器上获得上传进度呢?

  • 在我的ReactJs应用程序中,我使用Axios将文件上传为多部分/表单数据。有什么方法可以让我追踪文件上传的进度?

  • 问题内容: 当用户将文件上传到我的Web应用程序时,我想显示比gif动画更有意义的内容。我有什么可能性? 编辑:我正在使用.Net,但我不介意是否有人向我展示平台不可知的版本。 问题答案: 以下是一些常用JavaScript工具包的几种版本。 Mootools- http: //digitarald.de/project/fancyupload/ Extjs- http: //extjs.com/