0

我是 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 很陌生,如果您认为对您有用,请随时使用该代码

感谢您的时间

4

1 回答 1

0

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

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

这会导致明显的问题:

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

而不是发送 a Bitmap,您应该将文件作为 an 打开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);
}
于 2013-03-31T22:19:55.643 回答