【问题标题】:What is the simplest way to upload an image to my server from an Android phone从Android手机将图像上传到我的服务器的最简单方法是什么
【发布时间】:2011-08-23 20:19:09
【问题描述】:

我研究这个话题已经有一段时间了,但我一无所获。我购买的书籍和我找到的每个示例/博客都解释了如何使用 HttpClient、HttpPost 和 MultipartEntity 对象来上传文件。每当我使用这种方法时,都会发生以下几件事中的一件:

  1. 我的应用程序将崩溃。 Android 告诉我应用程序意外停止,我必须强制关闭它。

  2. 如果我使用包含 MultipartEntity 的代码,但不包含图像文件(使用 addPart()),则我的 PHP 服务器会接收 POST 数据。

我需要一种简单直接的方法来完成此过程。我什至尝试过 FTP,我会尝试使用我拥有的 FTPClient 示例代码,但到目前为止我一无所获,通常上传文件是一项非常简单的任务。

如果有人可以帮助我,请给我回复。这个项目最难的部分是理解正确的程序,因为我从网上看到的几乎每个来源中都找到了很多不同类型的代码。这个题目好像没有标准,很郁闷。

【问题讨论】:

  • 对于上述情况 1,您是否在主线程上进行网络连接?当您的应用程序崩溃时是否有堆栈跟踪?图片尺寸是多少?

标签: android file-upload


【解决方案1】:

我已经在我的几个 Android 项目中使用了这段代码,它没有引起任何问题。您可以根据需要对其进行修改。它使用HttpMime-4.1.1,它是HttpCore 的一部分。希望它也对你有用



/***
     * Execute multi part request especially for thing related to byte[]
     * @param url The destination URL
     * @param byteArray The byte to upload
     * @param values Additional key/value pair that you want to add
     * @param fileImage The image file name
     * @param imageFileKey The form key for the bytes that you are uploading
     * @return
     * @throws Exception
     */
    public static HttpResponse executeMultipartPost(String url, byte[] byteArray, 
            HashMap<String,  StringBody> values, 
            String fileImage, String imageFileKey)throws Exception {
        HttpPost postRequest = new HttpPost(url); 
        HttpClient httpClient = new DefaultHttpClient();

        Set<Map.Entry<String, StringBody>> entries = values.entrySet();
        MultipartEntity multipartContent = new MultipartEntity(); 

        for(Map.Entry<String, StringBody> current : entries) {
            multipartContent.addPart(current.getKey(), current.getValue());
        }

        InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(byteArray), 
                "image/jpeg", fileImage);
        multipartContent.addPart(imageFileKey, isb);

        postRequest.setEntity(multipartContent);
        HttpResponse res = httpClient.execute(postRequest);
        return res;
    }

【讨论】:

    【解决方案2】:

    确保您在 xml 文件中设置了您的权限。通常打开套接字和发送数据需要您在应用程序上设置比默认权限更高级别的权限

    【讨论】:

      【解决方案3】:

      你似乎已经拥有了几乎所有的武器;你是从一个新线程发送 POST 请求吗?我猜你不是,这将是强制关闭的原因(即挂在应用程序的主线程上)。

      如果不是这样,你能显示一些代码吗?

      【讨论】:

        猜你喜欢
        • 2015-05-04
        • 1970-01-01
        • 2012-08-24
        • 2023-02-07
        • 1970-01-01
        • 1970-01-01
        • 2014-08-05
        • 2021-12-13
        • 1970-01-01
        相关资源
        最近更新 更多