从Android设备上传图像到服务器

时间:2014-04-10 03:10:18

标签: android asp.net web

我们目前需要一种工具,可以将Android设备拍摄的照片直接上传到我们的服务器,而无需创建Android应用。这可以在Web应用程序中完成吗?我已经尝试了getusermedia API但没有成功。

1 个答案:

答案 0 :(得分:0)

现在你可以让这个任务更简单,更有用我设计了一个名为ImageUploaderUtility的类,它将图像上传到远程网络服务器。 ImageUploadUtility有一些简单的方法,您只需传递要上传的图像名称即可。

除此之外,这里的关键点是这个类需要在AsynTask中执行,这样才能确保整个图像上传过程不会冻结你的UI。

我使用了同样的过去项目并进行了扩展。

首先要理解的是我在BlogPostExampleActivity中创建了内部类,它是从AsyncTask扩展而来的,这个内部类将调用上传图像的方法,该方法在ImageUploader Utility中声明和定义,这一切都不是那么简单。 / p>

查看代码,如果您对此无法理解,请告诉我。

private class ImageUploaderTask extends AsyncTask<String, Integer, Void>{
    @Override
    protected void onPreExecute()
    {
            simpleWaitDialog = ProgressDialog.show(BlogPostExamplesActivity.this, "Wait", "Uploading Image");
    }
    @Override
    protected Void doInBackground(String... params){
            new ImageUploadUtility().uploadSingleImage(params[0]);
            return null;
    }
    @Override
    protected void onPostExecute(Void result){
            simpleWaitDialog.dismiss();
    }

}

现在ImageUploaderUtility.java

package gargi.blogpostexamples.webservice;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;import org.apache.commons.httpclient.methods.multipart.FilePart;import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;import org.apache.commons.httpclient.methods.multipart.Part;import org.apache.commons.httpclient.methods.multipart.StringPart;import android.os.Environment;import android.util.Log;class ImageUploadUtility {/** * Simple Utility Method gets called from other class to start uploading the image * @param fileNameToUpload name of the file to upload */public void uploadSingleImage(String fileNameToUpload){  try {  doUploadinBackground(getBytesFromFile(new File(Environment.getExternalStorageDirectory(),fileNameToUpload)), fileNameToUpload); } catch (IOException e) {  // TODO Auto-generated catch block  e.printStackTrace(); } catch (Exception e) {  // TODO Auto-generated catch block  e.printStackTrace(); }}/** * Method uploads the image using http multipart form data. * We are not using the default httpclient coming with android we are using the new from apache * they are placed in libs folder of the application * * @param imageData * @param filename * @return * @throws Exception */static boolean doUploadinBackground(final byte[] imageData, String filename) throws Exception{   String responseString = null;   PostMethod method;   method = new PostMethod("your url to upload");       org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();       client.getHttpConnectionManager().getParams().setConnectionTimeout(               100000);       FilePart photo = new FilePart("userfile", new ByteArrayPartSource(           filename, imageData));       photo.setContentType("image/jpeg");       photo.setCharSet(null);       String s  =  new String(imageData);       Part[] parts = {               new StringPart("latitude", "123456"),               new StringPart("longitude","12.123567"),               new StringPart("imei","1234567899"),               new StringPart("to_email","some email"),               photo               };       method.setRequestEntity(new MultipartRequestEntity(parts, method               .getParams()));       client.executeMethod(method);       responseString = method.getResponseBodyAsString();       method.releaseConnection();       Log.e("httpPost", "Response status: " + responseString);   if (responseString.equals("SUCCESS")) {       return true;   } else {       return false;   } }/** * Simple Reads the image file and converts them to Bytes * * @param file name of the file * @return byte array which is converted from the image * @throws IOException */public static byte[] getBytesFromFile(File file) throws IOException {  InputStream is = new FileInputStream(file);  // Get the size of the file  long length = file.length();  // You cannot create an array using a long type.  // It needs to be an int type.  // Before converting to an int type, check  // to ensure that file is not larger than Integer.MAX_VALUE.  if (length > Integer.MAX_VALUE) {    // File is too large  }  // Create the byte array to hold the data  byte[] bytes = new byte[(int)length];  // Read in the bytes  int offset = 0;  int numRead = 0;  while (offset < bytes.length      && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {    offset += numRead;  }  // Ensure all the bytes have been read in  if (offset < bytes.length) {    throw new IOException("Could not completely read file "+file.getName());  }  // Close the input stream and return bytes  is.close();  return bytes;}}

所以现在就是这样,这件事的坏处是我已经习惯了这项活动中的内心课,我不知道为什么但我感觉不太好,所以下次我会尝试制作一个从AysncTask扩展的类,并在现有的例子中使用它。

除此之外,如果您觉得可以通过其他方式进行改进,请不要忘记将其留在评论中。

最后但不是列表,您可以从此link下载完整的示例。