我一直在寻找一个程序来上传我用相机拍摄的照片,并存储在位图中到我自己的网站上。我尝试过跟随代码,但没有成功。
public void onClick(View v) {
ByteArrayOutputStream bytearrayStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 90, bytearrayStream);
byte [] byteArray = bytearrayStream.toByteArray();
String byteArrayToString = Base64.encodeBytes(byteArray);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image", byteArrayToString));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebsite.com/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
stream = entity.getContent();
Toast text = Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG);
text.show();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
Toast text = Toast.makeText(getApplicationContext(), "FOUT", Toast.LENGTH_LONG);
text.show();
}
}我在网站端使用的php代码是
<?php
$base=$_REQUEST['image'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$file = fopen('test.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src=test.jpg />';
?>如果我在本地主机上尝试php文件,它会生成一个test.jpg。所以我认为如果$_REQUEST['image']不是null,就会创建正确的文件。
如果try-area中没有错误,我的area程序会显示一个toasttext 'OK‘。如果有错误,它会显示'FOUT‘。在我的Xperia上测试时,总是显示OK...
有什么建议吗?
发布于 2012-04-27 12:46:39
尝尝这个
public void executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://www.mywebsite.com/upload_image.phpamp");
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
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
Log.e(e.getClass().getName(), e.getMessage());
}
}https://stackoverflow.com/questions/10334109
复制相似问题