我正在尝试通过相机将图像捕获上传到服务器.服务器发送响应代码= 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");
Hashtableirs = new Hashtableirs.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,bufferSize);
while (bytesRead > 0) {
dos.write(buffer,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,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;
}
功能:
private String getBoundaryMessage(String boundary,Hashtablearams,String fileField,String fileName,String fileType) {
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
Enumerationarams.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();
}
最佳答案
我用这个:
public class HttpClient extends AsyncTaskarams) {
for (File file : files) {
foto = "/sdcard/CameraExample/" + file.getName();
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urll);
multipartentity mpEntity = new multipartentity(
HttpMultipartMode.broWSER_COMPATIBLE);
mpEntity.addPart("form_file",new FileBody(file,"image/jpeg"));
httppost.setEntity(mpEntity);
HttpResponse response;
try {
response = httpclient.execute(httppost);
httpentity resEntity = response.getEntity();
if (resEntity != null) {
}
if (resEntity != null) {
resEntity.consumeContent();
}
} catch (ClientProtocolException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
}
return null;
}
protected void onPostExecute(Long unused) {
progressDialog.dismiss();
((Runnable) ctx ).run();
super.onPostExecute(unused);
}
protected void onPreExecute() {
progressDialog = new ProgressDialog(ctx);
progressDialog.setProgressstyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Загрузка фото...");
progressDialog.setProgress(0);
progressDialog.setMax(count);
progressDialog.show();
}
}
此代码使用该库:
import org.apache.http.httpentity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.multipartentity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.james.mime4j.message.Message;
你可以在谷歌找到这个.如果你没找到 – 我可以发给你这个库.