【问题标题】:android - file uploading via android http serverandroid - 通过 android http 服务器上传文件
【发布时间】:2013-04-19 13:05:56
【问题描述】:

你好

我尝试通过 HTTP 服务器将文件上传到 android,

我已经制作了 HTML 表单来上传文件,但是如何接收该文件以存储在 SDCard 中?

我只收到文件名,没有别的。

如何接收该文件?

【问题讨论】:

  • 你不会得到文件..你只会得到文件名..将路径传递给多部分
  • @sheetal 如何将该文件传递给多部分?我已经在 html 表单中添加了enctype="multipart/form-data"
  • 使用 Apache 的多部分库
  • @sheetal 在我的例子中,android 本身就是一个服务器。我想接收使用 html 表单通过用户发送的文件。知道怎么做吗?

标签: android forms http upload


【解决方案1】:
      MultipartEntity entity = new MultipartEntity();
  entity.addPart("type", new StringBody("photo"));
  entity.addPart("data", new FileBody(new File(filepath));
  httppost.setEntity(entity);
  HttpResponse response = httpclient.execute(httppost);

比阅读响应 这是参考here

或在没有库多部分的情况下使用此示例 here

【讨论】:

    【解决方案2】:
    private void uploadFile(File file) throws IOException {
        Log.i(TAG, "Uploading " + file);
        String videoName = file.getParentFile().getName();
    
        AndroidHttpClient httpclient = AndroidHttpClient.newInstance(GoProLive.TAG);
        try {
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), ConnectTimeout);
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), DataTimeout);
            HttpPost post = new HttpPost(
                    String.format("http://" + ServerName + "/upload/%s/%s", user.getUsername(), file.getName()));
            post.setEntity(new FileEntity(file, "application/octet-stream"));
    
            SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT, Locale.US);
            df.applyPattern("EEE, dd MMM yyyy HH:mm:ss z");
            post.setHeader("Last-Modified", df.format(new Date(file.lastModified())));
            HttpResponse httpResponse = executePost(httpclient, post);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                file.delete();
            } else {
                throw new HttpException("Failed to upload file " + file.getAbsolutePath(), statusCode);
            }
        } finally {
            httpclient.close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2014-02-12
      • 2016-10-22
      • 1970-01-01
      • 2012-09-28
      • 2011-06-25
      • 1970-01-01
      相关资源
      最近更新 更多