嗨,我正在開發一個應用程序,其中包括攝像頭圖像,我需要發送圖像,同時捕獲到PHP服務器,在我們的設置有布爾選項爲「AutoUploadPic」,當我們將開關設置爲是,那麼只有它應該上傳到服務器,如果它設置爲否,它不應該上傳。你能幫我解決這個問題嗎?如何將捕獲的圖像發送到服務器?
以下是上述查詢的iphone代碼,我可以像android一樣獲得。
嗨,我正在開發一個應用程序,其中包括攝像頭圖像,我需要發送圖像,同時捕獲到PHP服務器,在我們的設置有布爾選項爲「AutoUploadPic」,當我們將開關設置爲是,那麼只有它應該上傳到服務器,如果它設置爲否,它不應該上傳。你能幫我解決這個問題嗎?如何將捕獲的圖像發送到服務器?
以下是上述查詢的iphone代碼,我可以像android一樣獲得。
爲什麼你不能將你的位圖轉換成字節數組並傳遞給你的服務器。這是將位圖發送到服務器的代碼?
請在AsyncTask中做這些事情。
public class UploadPicture extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// show your progress bar
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// wrap up all your upload code here..
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// stop your progress bar
}
}
調用這個類檢查你的布爾後:
if(AutoUploadPic)
{
new UploadPicture().execute();
}
else
{
// Your code here..
}
//做在doInBackground級以下:
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// Preview_bitmap是你需要發送到一個服務器。我這裏壓縮和發送該服務器:
preview_bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
// constant.uploadImagesAPI是你的服務器網址:
HttpPost postRequest = new HttpPost(Constant.uploadImagesAPI
+ Constant.mDeviceID);
ByteArrayBody bab = new ByteArrayBody(data, ".jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder mUploadResponse = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
mUploadResponse = mUploadResponse.append(sResponse);
}
JSONObject mUploadResponseObject = new JSONObject(
mUploadResponse.toString());
mUploadResponseObject.getJSONArray("response");
try {
JSONArray jsonArray = mUploadResponseObject
.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
uploadStatus = jsonArray.getJSONObject(i)
.getJSONObject("send").getString("message");
uploadPhotoID = jsonArray.getJSONObject(i)
.getJSONObject("send").getString("id");
Constant.imageUploadedFlag = true;
}
} catch (Exception e) {
serverUploadException = true;
}
} catch (Exception e) {
}
// PHP代碼:
$to = $_REQUEST['deviceid'];
//$timestamp = $_REQUEST['timestamp'];
$path=PATH.'upload/';
//$path1=PATH.'newupload/';
//$name = $_FILES['image']['name'];
//$str=explode(".",$name);
//$imname=$str[0];
$filename=upload::save($_FILES['image']);
$file_name1= basename($filename);
$docroot= $_SERVER['DOCUMENT_ROOT'];
//$root=$docroot.'/newupload/';
$roots=$docroot.'/upload/';
$url = $path.$file_name1;
$send = $this->api->upload_images($to,$url);
if($send)
{
$json_response[] = array("send" =>
array("id"=> $send,
"message"=>"Message Sent Successfully",
"status"=>1));
}
echo json_encode(array ('response' =>$json_response));
break;
我該如何使用布爾條件 –
請檢查我的更新回答 –
上傳圖片通過多部分文件上傳到服務器。
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.os.AsyncTask;
public class MultiPartFileUpload {
private String filePath;
private String fileMimeType;
private String url;
private String attribute;
private AfterImageUploaded afterResult;
private CustomExceptions exception = null;
byte[] buffer;
byte[] data;
private Context context;
/**
* Provide mechanism to upload file with multi-part approach
*
* @param filePath
* : Absolute path of file
* @param fileMimeType
* : File mime-type e.g. image/jpeg
* @param url
* : URL to upload file
* @param attribute
* : Attribute where file would be placed
* @param afterResult
* : Implement this interface to receive result/errors
*/
public MultiPartFileUpload(Context context,String filePath, String fileMimeType,
String url, String attribute, AfterImageUploaded afterResult) {
this.context=context;
this.filePath = filePath;
this.fileMimeType = fileMimeType;
this.url = url;
this.attribute = attribute;
this.afterResult = afterResult;
UploadFileAsync uploadasynctask = new UploadFileAsync();
uploadasynctask.execute(url);
}
class UploadFileAsync extends AsyncTask<String, Integer, String> {
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values[0]);
}
@Override
protected String doInBackground(String... params) {
try {
String result = null;
ContentBody cbFile = null;
HttpClient httpclient = new DefaultHttpClient();
System.out.println("url:"+url);
HttpPost httppost = new HttpPost(url);
httppost.setHeader("partnerKey",
"39f1a112ed3b4a3537c1e05766e91d2f425a8d97");
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("image", new FileBody(new File(filePath)));
}
try {
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("response>>>>::"+ response.getStatusLine());
System.out.println("--------------------------------------");
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
} else {
throw new CustomExceptions("Connection error: "
+ response.getStatusLine().getStatusCode()
+ ":" + response.getStatusLine());
}
} catch (ClientProtocolException e) {
throw new CustomExceptions("Protocol Exception");
} catch (ParseException e) {
throw new CustomExceptions("Parse Exception");
} catch (IOException e) {
e.printStackTrace();
throw new CustomExceptions("IO Exception");
}
httpclient.getConnectionManager().shutdown();
return result;
// return postFile(); publishProgress(10)
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
afterResult.doAfterResult(result, exception);
}
}
public interface AfterImageUploaded {
public void doAfterResult(String result, Exceptions e);
}
}
你到目前爲止已經嘗試了什麼Raghu? –
那麼,既然你使用PHP和可能是一個Web服務器,你必須實現一個HTTP上傳。這裏有什麼問題? – arkascha