您好我正在开发一个包含相机图像的应用程序,我需要在捕获到php服务器时发送图像,在我们的设置中,当我们将开关设置为是时,布尔选项为“AutoUploadPic”,然后只应将其上传到服务器,如果设置为no,则不应上传。你可以帮我解决这个问题。
以下是上述查询的iphone代码,我可以获得与android相同的内容。
答案 0 :(得分:1)
为什么不能将位图转换为字节数组并将其传递给服务器。以下是将位图发送到服务器的代码?
请在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是您的服务器URL:
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;
答案 1 :(得分:0)
通过多部分文件上传将图片上传到服务器。
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);
}
}