【问题标题】:Android:Problems uploading an image to a Web Serbice with Apache ServerAndroid:使用 Apache 服务器将图像上传到 Web 服务时出现问题
【发布时间】:2013-03-22 00:57:52
【问题描述】:

我是 Android 和 Web 服务方面的新手,尤其是这些方面的新手,我正在尝试使用 Web 服务创建一个 Web 服务,以便存储从 Android 应用发送的图像。但是,我在将图像上传到服务器时遇到问题,并且没有显示。应该存放在哪里?另一个问题是,即使我创建了一个 Web 服务,它也只显示 HelloWorld,它最初是在 NetBeans 中创建的。 这是logcat日志:

04-01 00:03:55.831: E/SpannableStringBuilder(4384): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-01 00:03:55.831: E/SpannableStringBuilder(4384): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
04-01 00:04:55.792: W/IInputConnectionWrapper(4384): getSelectedText on inactive InputConnection
04-01 00:04:55.792: W/IInputConnectionWrapper(4384): setComposingText on inactive InputConnection
04-01 00:05:45.074: I/System.out(4555): Not a DRM File, opening notmally
04-01 00:05:45.074: I/System.out(4555): buffer returned 
04-01 00:05:45.089: D/dalvikvm(4555): GC_FOR_ALLOC freed 79K, 9% free 7518K/8195K, paused 17ms, total 17ms
04-01 00:05:45.097: I/dalvikvm-heap(4555): Grow heap (frag case) to 12.278MB for 4579316-byte allocation
04-01 00:05:45.113: D/dalvikvm(4555): GC_CONCURRENT freed 1K, 6% free 11988K/12679K, paused 2ms+2ms, total 18ms
04-01 00:05:45.285: D/libEGL(4555): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
04-01 00:05:45.285: D/libEGL(4555): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
04-01 00:05:45.292: D/libEGL(4555): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
04-01 00:05:45.371: D/OpenGLRenderer(4555): Enabling debug mode 0
04-01 00:05:45.691: I/System.out(4555): Status is HTTP/1.1 200 OK
04-01 00:05:45.691: I/System.out(4555): Response: <!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <title>JSP Page</title>    </head>    <body>        <h1>Hello World!</h1>    </body></html>

这是使用 NetBeans 和 Apache Tomcat 创建的 Web 服务,它应该检索图像。我不知道为什么,但是当我启动服务器时它只显示 HelloWorld

@Path("generic")
public class GenericResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GenericResource
     */
    public GenericResource() {
    }

    /**
     * Retrieves representation of an instance of za.org.droid.GenericResource
     * @return an instance of java.lang.String
     */
    @POST
@Path("/images")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response imageUpload(@FormDataParam("image") InputStream hereIsImage, @FormDataParam("image") FormDataContentDisposition hereIsName) {
    String path = System.getenv("HOME")+"/tmp/";
    if(hereIsName.getSize()==0) {
        return Response.status(500).entity("image parameter is missing").build();
    }
    String name = hereIsName.getFileName();
    path += name;

    try {
        OutputStream out = new FileOutputStream(new File(path));
        int read;
        byte[] bytes = new byte[1024];
        while ((read = hereIsImage.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        return Response.status(500).entity(name + " was not uploaded\n"+e.getMessage()).build();
    }
    return Response.status(200).entity(name + " was uploaded").build();
}
}

最后是 Android 应用程序的代码,它从 SDCard 中获取图像并将其发送到服务器。

public class MainActivity extends Activity{
    Bitmap bm;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        bm = BitmapFactory.decodeFile("/sdcard/DCIM/FinalM8.JPG");
        if(bm==null)
            throw new Exception("no picture!");
        new MyAsyncTask().execute();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... arg0) {
    // TODO Auto-generated method stub
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 50, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = 
            new HttpPost("http://192.168.1.35:8080/WebApplication4");
        ByteArrayBody bab = new ByteArrayBody(data, "FinalM8.JPG");
        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("image", bab);
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        System.out.println("Status is "+response.getStatusLine());
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        System.out.println("Response: " + s);
    } catch (Exception e) {
        // handle exception here
        e.printStackTrace();
    }
    return null;
}
}
}

我会很感激一些帮助,因为我对 WebServices 很陌生,如果您认为对您有用,请随时使用该代码

感谢您的宝贵时间

【问题讨论】:

标签: java android web-services tomcat upload


【解决方案1】:

首先,我在 Android 端没有看到任何 OutOfMemoryError,但这不是您应该上传文件的方式。

您正在尝试从 SD 卡中读取文件并将其解压缩为 Bitmap,然后将其重新压缩为 .jpg 字节数组并上传。

这会导致明显的问题:

  1. Bitmap 对于许多设备来说太大,并导致 OutOfMemoryError
  2. 您发送的图像将与原始图像不同,因为 解码,然后编码。
  3. 不要使用硬编码的 SD 卡路径,而是考虑使用: Environment.getExternalStorageDirectory()

您应该将文件作为InputStream 打开并发送,而不是发送Bitmap

示例

String url = Environment.getExternalStorageDirectory() + "/DCIM/FinalM8.JPG";
File f_path = new File(url);
InputStream fis = new BufferedInputStream(new FileInputStream(f_path));
int d;
while ((d = fis.read()) != -1) {
    bos.write(d);
}

【讨论】:

  • 嗨,大卫,感谢您的提示。但是在这种情况下,这不是问题(目前)。问题仍然存在,理论上设备发送图像但服务器中没有图像或文件。
  • 我在 Android 设备上解决的问题可能是次要的,只要您确定 Android LogCat 中没有捕获到可以解释客户端上传完成失败的Exception。您是否有可能在 Android 上错过了 Exception?任何 Android 设备都能够在没有比例因子或OutOfMemmoryError 的情况下打开 SD 卡上的全尺寸图像是不常见的,特别是如果图像是由相机拍摄的。
  • 嗨大卫,将图像转换为位图的代码部分取自一个理论上有效的教程。正如我所说,我对 Web 服务非常陌生,但我猜是问题所在位于 Web 服务部分,因为它给 Android 设备的响应是消息“Hello World”(最初生成的部分代码,但我在 NetBeans 中删除了)
  • 是的。这对我来说很有意义。如果您确认 Android 中没有 Exception,请在 Web 服务正常工作后将此答案作为优化,因为该建议是合理的。祝凯瑟琳好运!
  • 再次感谢大卫,我在 logcat 中发布了状态,理论上设备正在连接到 web 服务 00:05:45.691: I/System.out(4555): Status is HTTP/1.1 200 OK
猜你喜欢
  • 2019-08-15
  • 2013-11-04
  • 1970-01-01
  • 2012-11-04
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多