Android:使用Apache Server将图像上载到Web服务时出现问题

时间:2013-03-31 22:14:12

标签: java android web-services tomcat upload

我是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 Service,以及应该检索图像的Web Service。我不知道为什么但是当我启动服务器时它只显示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很新,如果你认为对你有用,可以随意使用代码

感谢您的时间

1 个答案:

答案 0 :(得分:0)

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

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

这会导致明显的问题:

  1. Bitmap对于许多设备而言太大而导致 OutOfMemoryError
  2. 您发送的图片将与原始图片不同,因为 解码然后编码。
  3. 考虑使用以下方法,而不是SD卡的硬编码路径: Environment.getExternalStorageDirectory()
  4. 您应该将文件作为Bitmap打开并发送,而不是发送InputStream

    示例

    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);
    }