Android: Simple way to upload a picture to an image host

霸气de小男生 提交于 2019-12-11 13:48:59

问题


I d like to upload a picture to a host like: http://imagerz.com/ . Any sample for this? I can do a simple POST request, but how I can add the image content to my POST request?


回答1:


Here is a tutorial that tells you how to send a file via FTP to a server. File upload and download using Java

It shouldn't be very hard to "port" that code into android. (You may have to change some of the classes/methods as some of them may not be implemented in Android's lightweight VM).

There are also other image hosting services that should have an api that you could follow.

EDIT:

As you stated, you wanted to do this with a post request.

I found this great tutorial with the following code:

package com.commonsbook.chap9;
import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

public class HttpMultiPartFileUpload {
    private static String url =
      "http://localhost:8080/HttpServerSideApp/ProcessFileUpload.jsp";

    public static void main(String[] args) throws IOException {
        HttpClient client = new HttpClient();
        MultipartPostMethod mPost = new MultipartPostMethod(url);
        client.setConnectionTimeout(8000);

        // Send any XML file as the body of the POST request
        File f1 = new File("students.xml");
        File f2 = new File("academy.xml");
        File f3 = new File("academyRules.xml");

        System.out.println("File1 Length = " + f1.length());
        System.out.println("File2 Length = " + f2.length());
        System.out.println("File3 Length = " + f3.length());

        mPost.addParameter(f1.getName(), f1);
        mPost.addParameter(f2.getName(), f2);
        mPost.addParameter(f3.getName(), f3);

        int statusCode1 = client.executeMethod(mPost);

        System.out.println("statusLine>>>" + mPost.getStatusLine());
        mPost.releaseConnection();
    }
}

Source: http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload

The same issues about porting this code to android as I stated above apply.



来源:https://stackoverflow.com/questions/5476625/android-simple-way-to-upload-a-picture-to-an-image-host

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!