【问题标题】:How to send an image from android to servlet and then store it如何将图像从android发送到servlet然后存储
【发布时间】:2011-09-12 17:06:48
【问题描述】:

我正在尝试通过 http 将照片发送到我的服务器。因此,我将图像转换为字节,然后将其作为名称值对发送。这是我这样做的代码。现在我的问题是服务器端,我如何从收到的字节字符串中重新创建和存储图像

我也在使用 java servlet

安卓上的代码

ByteArrayOutputStream baos = new ByteArrayOutputStream();
pinnedV.getPhoto().compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();

List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("photo",new String(b)));

HttpClient httpclient = new DefaultHttpClient();  
    HttpPost request = new HttpPost(URL);

    try {
        request.setEntity(new UrlEncodedFormEntity(params));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    ResponseHandler<String> handler = new BasicResponseHandler();  
     try {  
         result = httpclient.execute(request, handler);  
     } catch (ClientProtocolException e) {  
         e.printStackTrace();  
     } catch (IOException e) {  
         e.printStackTrace();  
    }  

服务器上的代码

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String fromClientphoto= request.getParameter("photo");
byte[] b = fromClientphoto.getBytes();

FileOutputStream fos = new FileOutputStream("D:\\img.png");
     fos.write(b);
     fos.close(); 
}

上面的代码写入了一个文件,但它不会作为图像打开。这也是byte[] b = fromClientphoto.getBytes(); 转换回与安卓手机相同字节的正确方法吗?有什么想法吗?

【问题讨论】:

  • 有什么问题?你有代码来做这两个操作。
  • @Haphazard 基本上错误是我的 bim 对象为空 -
  • 我对@9​​87654324@一无所知,所以我怀疑我能帮上什么忙。
  • @Haphazard 但我是否以正确的方式发送图像,如果有不同的方式你能帮忙吗?
  • 您能否确认是否有任何数据进入服务器?调试或打印出b 数组的大小。

标签: java android image servlets


【解决方案1】:

您不应将文件(即图像)作为常规名称-值参数从您的设备发送并使用request.getParameter(name); 读取它。

改为:

  • 在 Android 端,使用MultipartEntity(参见other questions)。它已经是 httpclient 的一部分。
  • 在服务器端,您可以找到有用的apache-fileupload(或其他可以帮助您阅读您在 servlet 中收到的多部分内容的库)

【讨论】:

    【解决方案2】:

    不要打扰工具包图像,只需将内容写入文件..

    您可以将图像发布到 android 之外的 Servlet 吗?设置一个通过基本 HTML 表单执行相同操作的虚拟页面,将问题分解为越来越小的部分,直到找出导致问题的部分...

    【讨论】:

    • 所以图像被转换为​​字节,然后在安卓手机上用它们字节生成一个字符串......然后服务器端我调用上面的方法从字符串转换为字节.. .然后我把它写到一个文件中
    猜你喜欢
    • 2016-08-02
    • 2011-05-02
    • 2015-07-26
    • 2011-09-13
    • 1970-01-01
    • 2014-06-29
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多