用户可以通过相机在android端拍摄5-6张照片。所以,我使用了ACTION_IMAGE_CAPTURE。在onActivityResult中,我这样做是为了收集相机拍摄的图像的位图。假设首先拍摄的照片和第二张照片如下所示。
if(requestCode == 1)
{
bitMap1 = (Bitmap)extras.get("data");
imageView1.setImageBitmap(bitMap1);
globalvar = 2;
}
if(requestCode == 2)
{
bitMap1 = (Bitmap)extras.get("data");
imageView2.setImageBitmap(bitMap2);
globalvar = 2;
}
要将这些图像发送到php服务器,我会执行以下操作..
protected String doInBackground(Integer... args) {
// Building Parameters
ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
bitMap1.compress(Bitmap.CompressFormat.JPEG, 90, bao1);
byte [] bytearray1 = bao1.toByteArray();
String stringba1 = Base64.encode(bytearray1);
ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
bitMap2.compress(Bitmap.CompressFormat.JPEG, 90, bao2);
byte [] bytearray2 = bao2.toByteArray();
String stringba2 = Base64.encode(bytearray2);
String parameter1 = "tenant";
String parameter2 = "price";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("person",parameter1));
params.add(new BasicNameValuePair("price",parameter2));
params.add(new BasicNameValuePair("image1",stringba1));
params.add(new BasicNameValuePair("image2",stringba2));
JSONObject json = jParser.makeHttpRequest(requiredurl, "POST", params);
Log.d("Details", json.toString());
int success = json.getInt("connected");
if (success == 1) {
//blah blah
}
}
这是 makeHttpRequest()方法:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
................
....................... // Here the result is extracted and made it to json object
.............................
// return JSON
return jObj; // returning the json object to the method that calls.
}
以下是php代码段:
$name = $_POST[person];
$price = $_POST[price];
$binary1 = base64_decode($image2);
$binary2 = base64_decode($image2);
$file1 = tempnam($uploadPath, 'image2');
$fp1 = fopen($file1, 'wb');
fwrite($fp1, $binary1);
fclose($fp1);
.................
............................
但是我无法将图像存储在服务器端文件夹中。甚至我在一些链接中看到,在上传多个图像时,Base64不是更好的方式。有人可以建议我如何进行?已经看过this和许多其他链接,但无法获得如何继续我的要求,因为我甚至必须发送一些数据(如人名,价格)和图像。非常感谢任何帮助。
注意:即使有人可以建议我如何在服务器文件夹中保存上面的临时文件($ file1),我也会非常感激。
答案 0 :(得分:2)
您是否考虑过使用FTP代替目前的方法? apache中有一个名为Apache的commons-net-ftp库的库,可以轻松完成工作。
这是我很久以前在stackoverflow上提出的一个问题。我以前实现了几乎相同的代码,但我发现FTP方法更容易上传文件到服务器。
@TemporaryNickName如何与该图像一起发送其他数据。此外,我的图像数据是位图,而不是uri。如何根据我目前的事情来实现它?
*有很多教程向您展示如何将位图转换为图像文件(这是保存文件临时和FTP完成后立即删除的方法),此外,当您使用默认内置相机应用程序拍摄照片时,您的图像自动保存。 好的发送数据应该单独完成,在这种情况下,我会编写一个带有$ _POST的PHP脚本来接收数据,而不是将其保存到数据库中或将其写入XML *
要保存上传的文件,请使用
move_uploaded_file($src, $path);
答案 1 :(得分:2)
要发送多种类型的数据,请使用MultipartEntity
(来自问题中提供的链接)而不是URLEncodedEntity
。我们的想法是MultipartEntity
只包含不同类型的主体(例如StringBody
,FileBody
等)。因此,如果您需要在Base64中发送图片,请将其StringBody
添加到MultipartEntity
(应使用setEntity
将其设置为您的请求的实体。)
虽然,我强烈建议您将位图保存在磁盘(SD卡)上,然后使用FileBody
。它会为你节省大量内存(使用Base64你必须一次加载所有图像)和...如果用户在上传时关闭你的应用程序怎么办?你将永远失去你的位图。
P.S。不要忘记使用Service
上传任务。
答案 2 :(得分:1)
这是我的代码片段,希望这会有所帮助:
private class AsyncTask1 extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
boolean response = false;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileBody bin = new FileBody(new File("temp"));
File tempImg = new File("sdcard/signature.jpg");
if(tempImg.exists())
{
checkimgfile=checkimgfile+"LPA"+tempImg;
bin = new FileBody(tempImg, "image/jpg");
reqEntity.addPart("txt_sign_lpa", bin);
reqEntity.addPart("count_lpa",new StringBody("1"));
}
else
{
reqEntity.addPart("count_lpa",new StringBody("0"));
}
FileBody bin1 = new FileBody(new File("temp"));
File tempImg1 = new File("sdcard/signature2.jpg");
if(tempImg1.exists())
{
checkimgfile=checkimgfile+"subject"+tempImg1;
bin1 = new FileBody(tempImg1, "image/jpg");
reqEntity.addPart("txt_sign", bin1);
reqEntity.addPart("count_subject",new StringBody("1"));
}
reqEntity.addPart("count",new StringBody("0"));
reqEntity.addPart("name",new StringBody("Shaili"));
reqEntity.addPart("age",new StringBody("47"));
try
{
ConnectivityManager cm =
(ConnectivityManager)getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork!=null && activeNetwork.isAvailable() && activeNetwork.isConnected())
{
String xml = "";
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 100000);
final HttpClient httpclient = new DefaultHttpClient(httpParameters);
final HttpPost httppost = new HttpPost("https://www.xyz.com/abc.php");//url where you want to post your data.
httppost.setParams(httpParameters);
httppost.setEntity(reqEntity);
httppost.addHeader("Accept", "text/html");
httppost.addHeader("Host", "www.xyz.com");
httppost.addHeader("User-Agent",
"Android ");
HttpResponse response1 = null;
String errMessage = "Error";
try {
response1 = httpclient.execute(httppost);
final HttpEntity resEntity = response1.getEntity();
InputStream content = resEntity.getContent();
BufferedReader b = new BufferedReader(new InputStreamReader(
content));
xml = XmlParser.getTrimmedResponse(b);
if (response1 != null){
if(Integer.toString(response1.getStatusLine().getStatusCode()).equals("200")){
return "success";
}
}
} catch (Exception e) {
e.printStackTrace();
errorstring=errorstring+e.getLocalizedMessage();
errMessage = "Network error";
return errMessage;
}
}
else if(activeNetwork==null)
{
return "Available";
}
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), "Network Connection not available", 1).show();
progressDialog.dismiss();
}
} catch (Exception e) {
errorstring=errorstring+e.getLocalizedMessage();
return "Network error";
}
return "abc";
}
protected void onPostExecute(String result) {
//do your stuff
}
}