来自android的图像servlet上传.....这个代码有什么问题

时间:2011-05-08 03:53:30

标签: android image servlets base64

这是android代码

public class upload extends Activity {
    InputStream is;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        //Bitmap bitmapOrg = BitmapFact0ory.decodeResource(getResources(),
        //R.drawable.a1);
        Bitmap bitmapOrg = BitmapFactory.decodeFile("/sdcard/pradeep.jpg");
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte [] ba = bao.toByteArray();
        String ba1=Base64.encodeBytes(ba);
        ArrayList<NameValuePair> nameValuePairs = new
        ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("image",ba1));
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new
            HttpPost("http://10.0.2.2:8080/upload/uploadedimg");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
    }
}

继承我的Servlet代码......

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    InputStream in = request.getInputStream();
    BufferedReader r = new BufferedReader(new InputStreamReader(in));
    StringBuffer buf = new StringBuffer();
    String line;

    //Read the BufferedReader out and receives String data
    while ((line = r.readLine())!=null) {
        buf.append(line);
    }
    String imageString = buf.toString();

    byte[] imageByteArray = Base64.decode(imageString);
    FileOutputStream f = new FileOutputStream("C:/test.jpg");
    f.write(imageByteArray);
    f.close();
}

这些代码都不会产生错误,但是当我运行它们时,我看不到服务器上的图像。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

在将图像分配给字符串之前,您正在创建名称值对:在将图像分配给字符串之后,需要创建名称值对。这就是服务器找不到文件的原因。

变化:

String ba1;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image",ba1));
    try
    {
         ba1=Base64.encodeBytes(ba);

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
     nameValuePairs.add(new BasicNameValuePair("image",Base64.encodeBytes(ba)));