如何使用POST或PUT上传http服务器部分文件?我可以使用所描述的解决方

时间:2011-10-19 08:35:59

标签: android http upload httpclient put

我有一项任务。在http服务器上传一部分文件(我必须跳过文件的开头)。

我该怎么办?你知道好的解决方案吗?

我可以使用自己的解决方案吗?这样安全吗?

我的解决方案。我创建了FileEntity的子类,它提供文件流并跳过文件的开头。

  1. 我把我的实体请求。

    HttpPut request = new HttpPut(this.uri);

    request.setEntity(new FileOfsetEntity(new File(getDestination()),“binary / octet-stream”,ofset));

  2. 我的FileOfsetEntity会跳过文件的开头。

    class FileOfsetEntity extends FileEntity {
    
    long ofset = 0;
    public FileOfsetEntity(File file, String contentType, long ofset) {
      super(file, contentType);
      this.ofset = ofset;
    }
    @Override
    public long getContentLength() {
      return this.file.length() - ofset;
    }
    @Override
    public InputStream getContent() throws IOException {
      FileInputStream in = new FileInputStream(this.file);
      long skiped = in.skip(ofset);
      Log.w("FileOfsetEntity.getContent","skiped = " + skiped);
      return in;
    }
    @Override
    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);
      long skiped = instream.skip(ofset);
      Log.w("FileOfsetEntity.writeTo","skiped = " + skiped);
      try {
          byte[] tmp = new byte[4096];
          int l;
          long readed = skiped;
          while ((l = instream.read(tmp)) != -1) {
              readed += l;
              outstream.write(tmp, 0, l);
              Log.v("FileOfsetEntity.writeTo",file.getAbsolutePath() + " readed = " + readed + " skiped = " + skiped);
          }
          outstream.flush();
      } finally {
          instream.close();
      } }}
    

1 个答案:

答案 0 :(得分:1)

我不确定这可能会失败或经历。

我建议,这样做的另一种方式。我认为你在上传之前就知道办公室了。

这是服务器的link to upload file

在此代码中,移动偏移量,然后开始将其写入流中。