我想在不使用上传按钮的情况下将图片上传到服务器,我将图像路径发送到该活动中的下一个活动,我们有图像预览..但我的问题是如何在不使用点击活动的情况下将该图像上传到服务器...预览图像应该上传到服务器..请帮帮我..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cam);
ImageView view = (ImageView) findViewById(R.id.imageView1);
image_path = getIntent().getStringExtra("path");
Bitmap bitmap1 = BitmapFactory.decodeFile(image_path);
//Log.i(path, "image path in cam activity");
view.setImageBitmap(bitmap1);
upLoadServerUri = "http://xxxhasdghs.com/apps/upload.php";
uploadFile(image_path);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
//dialog.dismiss();
//Log.e("uploadFile", "Source File not exist :"+image_path);
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("Source File not exist :"+ imagepath);
Toast.makeText(Cam.this, "Source File not exist :", Toast.LENGTH_SHORT).show();
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
// conn.setRequestProperty("image", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_img\";filename=\""
+ fileName + "\"" + lineEnd);
//Log.i("image value in php", mail);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
//messageText.setText(msg);
//Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
Toast.makeText(Cam.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("MalformedURLException Exception : check script url.");
// Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Toast.makeText(Cam.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
//messageText.setText("Got Exception : see logcat ");
//Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
Toast.makeText(Cam.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
logcat错误
03-12 12:59:23.703: E/AndroidRuntime(26390): FATAL EXCEPTION: AsyncTask #2
03-12 12:59:23.703: E/AndroidRuntime(26390): java.lang.RuntimeException: An error occured while executing doInBackground()
03-12 12:59:23.703: E/AndroidRuntime(26390): at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-12 12:59:23.703: E/AndroidRuntime(26390): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.lang.Thread.run(Thread.java:841)
03-12 12:59:23.703: E/AndroidRuntime(26390): Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.mime.MultipartEntity
03-12 12:59:23.703: E/AndroidRuntime(26390): at com.example.slimcell.CameraActivity$ImageUploadTask.doInBackground(CameraActivity.java:101)
03-12 12:59:23.703: E/AndroidRuntime(26390): at com.example.slimcell.CameraActivity$ImageUploadTask.doInBackground(CameraActivity.java:1)
03-12 12:59:23.703: E/AndroidRuntime(26390): at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
答案 0 :(得分:1)
首先,您必须将uploadfile方法放在asynctask中,并在oncreate活动方法中调用asynctask。在第二个活动中在onCreate()中调用此asynctask。您必须下载第三方jar文件才能使用here.
中的multipartEntity如果需要将ADT 17罐放入libs文件夹中,或者它们不会与apk一起打包。因此要么将它们放入库中,要么转到“配置构建路径”。" - >"订购和导出"然后点击你的罐子旁边的复选框。
class ImageUploadTask extends AsyncTask<Void, Void, String> {
private String webAddressToPost = "Your URL";
// private ProgressDialog dialog;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
dialog.setMessage("Uploading...");
dialog.show();
}
@Override
protected String doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(webAddressToPost);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String file = Base64.encodeBytes(data);
entity.addPart("uploaded", new StringBody(file));
entity.addPart("someOtherStringToSend", new StringBody("your string here"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
// something went wrong. connection with the server error
}
return null;
}
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "file uploaded",Toast.LENGTH_LONG).show();
}
}