将图片从Android上传到Web服务

5

如何使用SOAP上传图像文件到webservice?

我需要将其与SoapObject一起使用,以便webservice可以在其上下文中处理输入文件并为其提供新文件名。

如何实现? 有代码示例吗?

Yoav

1个回答

7
将您的图像文件转换为Base64字符串,并轻松地将字符串及其名称发送到Web服务。 您还需要代码示例吗?
public static String fileToBase64(String path) throws IOException {
    byte[] bytes = Utilities.fileToByteArray(path);
    return Base64.encodeBytes(bytes);
}

public static byte[] fileToByteArray(String path) throws IOException {
    File imagefile = new File(path);
    byte[] data = new byte[(int) imagefile.length()];
    FileInputStream fis = new FileInputStream(imagefile);
    fis.read(data);
    fis.close();
    return data;
}

public class MyImage  {
public String name;
public String content;
}

将您的对象作为JSON字符串发送到Web服务:

在您的活动中:

MyClass myClass = new MyClass();
myClass.name = "a.jpg";
myClass.content = fileToBase64("../../image.jpg");
sendMyObject(myClass);

private void sendMyObject(
        MyImage myImage ) throws Exception {
    // create json string from your object
    Gson gson = new Gson();
    String strJson = gson.toJson(myImage);
    //send your json string here
    //...

}

在您的Web服务中,将JSON字符串转换为MyClass的实际对象副本。
编辑:
您也可以忽略Json,并使用2个参数的Web服务方法:MyWebserviceMethod(string filename,string content); 将Base64字符串作为第二个参数传递。

你是如何实现你的Web服务的?它是一个.NET Web服务吗? - Bobs
你发送的是由JSON创建的“字符串”,而不是发送“JSON”对象。 - Bobs
1
添加属性("paramName",strJson) - Bobs
我需要哪个导入项才能使用Base64.encodeBytes函数?还是需要添加一个jar包? - Yoav
谢谢,我会在网络上寻找它。 - Yoav
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接