如何在Android中将图像上传到服务器?

Pra*_*dam 5 android file-upload image httprequest httpconnection

我正在尝试通过相机将图像捕获上传到服务器.服务器发送响应代码= 200但Image不上传到服务器.

代码是:

private boolean uploadData() {

    int count = this.forumThreadsB.size();
    for (int i = 0; i < count; i++)
    {
            if (isPhoto)
                message = "Uploading Shared Items " + (i + 1) + " of " + count;
            else
                message = "Uploading Shared Items " + (i + 1) + " of " + count;

            progressCount = (i * 1000)/count; 
            Hashtable<?, ?> threadD = (Hashtable<?, ?>)this.forumThreadsB.elementAt(i);

            String onlinePath = "http://xyx.com/;
            threadid = (String) threadD.get("devicethreadid");
            Hashtable<String, String> pairs = new Hashtable<String, String>();
            pairs.put("forumid",  threadD.get("lmsforumid").toString());
            pairs.put("topicid",  threadD.get("lmsthreadid").toString());
            pairs.put("clientid", LoginHelper.clientid);
            String fullfilepath = threadD.get("offlinepath").toString();
            int index = threadD.get("offlinepath").toString().lastIndexOf("/");

            String filename = fullfilepath.substring(index + 1);
            String filetype = "";

            if (filename.toLowerCase().contains(".png"))
                filetype = "image/png";
            else if (filename.toLowerCase().contains(".jpg"))
                filetype = "image/jpeg";
            else if (filename.toLowerCase().contains(".mp4"))
                filetype = "image/mp4";
            else if (filename.toLowerCase().contains(".3gp"))
                filetype = "image/3gpp";



            String boundaryMessage = getBoundaryMessage(BOUNDARY, pairs, fullfilepath, filename, filetype);
            String endBoundary = "\r\n--" + BOUNDARY + "--\r\n";

            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;

            try
            {
                URL url = new URL(onlinePath);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDARY);
                dos = new DataOutputStream( conn.getOutputStream() );
                dos.write( boundaryMessage.getBytes());
                File file = new File(fullfilepath.substring(6));
                FileInputStream fileInputStream = new FileInputStream(file);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                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);
                }
                dos.write(endBoundary.getBytes());
                dos.flush();
                dos.close();
                fileInputStream.close();
                } catch (IOException ioe) {
                    Log.e("SyncUploadDownloadHelper", "Cannot upload file: " + ioe.getMessage(), ioe);
                    //return false;
                }

                // Read response
                try {
                    int responseCode = conn.getResponseCode();
                    if(responseCode == 200){

                         SQLiteForumDAO forumDAO = new SQLiteForumDAO(mcontext) ;
                            ForumThreadDTO forumThreadDTO = forumDAO.selectThread(this.threadid);
                            if(downloadPath!=null && downloadPath.equalsIgnoreCase("null") && downloadPath.equalsIgnoreCase(""))
                            forumThreadDTO.offlinefilepath = downloadPath;
                            forumDAO.updateThread(forumThreadDTO);


                    }


                } catch (IOException ioex) {
                    Log.e("SyncUploadDownloadHelper", "Upload file failed: " + ioex.getMessage(), ioex);
                    //return false;
                } catch (Exception e) {
                    Log.e("SyncUploadDownloadHelper", "Upload file failed: " + e.getMessage(), e);
                    //return false;
                }

                if (i == (this.forumThreadsB.size() - 1)){
                    this.sendStatus = "true";
                    progressCount = 1000;
                    SyncUploadDownloadHelper.this.notifyObservers("SyncUploadDownloadHelper:UploadDataFinish");
                }
                else
                    SyncUploadDownloadHelper.this.notifyObservers("SyncUploadDownloadHelper:UploadData");

                //return true;

    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

功能:

private String getBoundaryMessage(String boundary, Hashtable<String, String> params, String fileField, String fileName, String fileType) {
      StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
      Enumeration<String> keys = params.keys();
      while(keys.hasMoreElements()) {
       String key = (String)keys.nextElement();
       String value = (String)params.get(key);

       System.out.println(key + ": " + value);

       res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")    
       .append("\r\n").append(value).append("\r\n").append("--").append(boundary).append("\r\n");
      }
      res.append("Content-Disposition: form-data; name=\"").append("file").append("\"; filename=\"").append(fileName).append("\"\r\n") 
      .append("Content-Type: ").append(fileType).append("\r\n\r\n");

      return res.toString();
     }
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中我捕获图像并将其保存到数据库.保存图像的路径用于上传图像文件.

Ant*_*ton 4

我用这个:

\n\n
public class HttpClient extends AsyncTask<Void, Integer, Long> {\n    private static final int PROGRESS_DIALOG = 0;\n\n    public ProgressDialog dialog;\n    public File file;\n    protected Long doInBackground(Void... params) {\n        for (File file : files) {\n\n            foto = "/sdcard/CameraExample/" + file.getName();\n            DefaultHttpClient httpclient = new DefaultHttpClient();\n\n            HttpPost httppost = new HttpPost(urll);\n\n\n\n            MultipartEntity mpEntity = new MultipartEntity(\n                    HttpMultipartMode.BROWSER_COMPATIBLE);\n\n            mpEntity.addPart("form_file", new FileBody(file, "image/jpeg"));\n\n            httppost.setEntity(mpEntity);\n\n            HttpResponse response;\n            try {\n\n                response = httpclient.execute(httppost);\n\n                HttpEntity resEntity = response.getEntity();\n\n                if (resEntity != null) {\n\n                }\n                if (resEntity != null) {\n                    resEntity.consumeContent();\n                }\n            } catch (ClientProtocolException e) {\n                e.printStackTrace();\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n\n\n\n        }\n        return null;\n    }\n\n    protected void onPostExecute(Long unused) {\n        progressDialog.dismiss();\n\n        ((Runnable) ctx ).run();\n\n        super.onPostExecute(unused);\n    }\n\n    protected void onPreExecute() {\n    progressDialog = new ProgressDialog(ctx);\n    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n    progressDialog.setMessage("\xd0\x97\xd0\xb0\xd0\xb3\xd1\x80\xd1\x83\xd0\xb7\xd0\xba\xd0\xb0 \xd1\x84\xd0\xbe\xd1\x82\xd0\xbe...");\n    progressDialog.setProgress(0);\n    progressDialog.setMax(count);\n    progressDialog.show();\n    }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用该库的代码:

\n\n
import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.mime.HttpMultipartMode;\nimport org.apache.http.entity.mime.MultipartEntity;\nimport org.apache.http.entity.mime.content.FileBody;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.util.EntityUtils;\nimport org.apache.james.mime4j.message.Message;\n
Run Code Online (Sandbox Code Playgroud)\n\n

你可以在谷歌中找到这个。如果您找不到 - 我可以向您发送该库。

\n