我必須構建一個應將圖片從手機發送到網絡服務器的應用程序。不幸的是,我真的不知道該怎麼做。有人可以幫我嗎?將圖片發送到網絡服務器
回答
做一個HTTP請求,你可以使用DefaultHttpClient類和
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://your.site/your/service");
// set some headers if needed
post.addHeader(....);
// and an eclosed entity to send
post.setEntity(....);
// send a request and get response (if needed)
InputStream responseStream = client.execute(post)..getEntity().getContent();
增加一個實體請求的方法取決於如何遠程serivice工作HttpPost類。
感謝Olegas,感謝示例代碼。我會嘗試一下,看看它是如何發展的。 – 2011-03-24 06:39:59
使用Web服務來實現此任務。
爲了在android中使用web服務,請訪問此鏈接。
不錯..,+1 ..... – Mudassir 2011-03-24 06:27:20
謝謝你一步一步的建議,Shashank。我會試試看看它是如何發展的。 – 2011-03-24 06:28:40
下面是我使用的圖像上傳到遠程服務器,使用原始套接字的代碼。 httpclient上的原始套接字的優點是可以顯示上傳進度條。
聲明:該代碼大部分主要來自stackoverflow。
/**
* Asynchronous task to upload file to server
*/
class UploadImageTask extends AsyncTask<File, Integer, Boolean> {
/** Upload file to this url */
private static final String UPLOAD_URL = "http://thibault-laptop:8080/report";
/** Send the file with this form name */
private static final String FIELD_FILE = "file";
private static final String FIELD_LATITUDE = "latitude";
private static final String FIELD_LONGITUDE = "longitude";
/**
* Prepare activity before upload
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
setProgressBarIndeterminateVisibility(true);
mConfirm.setEnabled(false);
mCancel.setEnabled(false);
showDialog(UPLOAD_PROGRESS_DIALOG);
}
/**
* Clean app state after upload is completed
*/
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
setProgressBarIndeterminateVisibility(false);
mConfirm.setEnabled(true);
mDialog.dismiss();
if (result) {
showDialog(UPLOAD_SUCCESS_DIALOG);
} else {
showDialog(UPLOAD_ERROR_DIALOG);
}
}
@Override
protected Boolean doInBackground(File... image) {
return doFileUpload(image[0], UPLOAD_URL);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values[0] == 0) {
mDialog.setTitle(getString(R.string.progress_dialog_title_uploading));
}
mDialog.setProgress(values[0]);
}
/**
* Upload given file to given url, using raw socket
* @see http://stackoverflow.com/questions/4966910/androidhow-to-upload-mp3-file-to-http-server
*
* @param file The file to upload
* @param uploadUrl The uri the file is to be uploaded
*
* @return boolean true is the upload succeeded
*/
private boolean doFileUpload(File file, String uploadUrl) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String separator = twoHyphens + boundary + lineEnd;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int sentBytes = 0;
long fileSize = file.length();
// The definitive url is of the kind:
// http://host/report/latitude,longitude
uploadUrl += "/" + mLocation.getLatitude() + "," + mLocation.getLongitude();
// Send request
try {
// Configure connection
URL url = new URL(uploadUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
publishProgress(0);
dos = new DataOutputStream(conn.getOutputStream());
// Send location params
writeFormField(dos, separator, FIELD_LATITUDE, "" + mLocation.getLatitude());
writeFormField(dos, separator, FIELD_LONGITUDE, "" + mLocation.getLongitude());
// Send multipart headers
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + FIELD_FILE + "\";filename=\""
+ file.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// Read file and create buffer
FileInputStream fileInputStream = new FileInputStream(file);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Send file data
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
// Write buffer to socket
dos.write(buffer, 0, bufferSize);
// Update progress dialog
sentBytes += bufferSize;
publishProgress((int)(sentBytes * 100/fileSize));
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);
dos.flush();
dos.close();
fileInputStream.close();
} catch (IOException ioe) {
Log.e(TAG, "Cannot upload file: " + ioe.getMessage(), ioe);
return false;
}
// Read response
try {
int responseCode = conn.getResponseCode();
return responseCode == 200;
} catch (IOException ioex) {
Log.e(TAG, "Upload file failed: " + ioex.getMessage(), ioex);
return false;
} catch (Exception e) {
Log.e(TAG, "Upload file failed: " + e.getMessage(), e);
return false;
}
}
private void writeFormField(DataOutputStream dos, String separator, String fieldName, String fieldValue) throws IOException
{
dos.writeBytes(separator);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"\r\n");
dos.writeBytes("\r\n");
dos.writeBytes(fieldValue);
dos.writeBytes("\r\n");
}
}
要開始上傳,請使用以下命令:
new UploadImageTask().execute(new File(imagePath));
我沒有使用Android的一個休息互聯網服務和DefaultHttpClient類。要創建一個樣本REST Web服務和Apache Tomcat上進行部署,請按照教程Vogella
爲了讓REST服務接受圖像,多內容的類型是在服務器端
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json")
public String uploadFile(@FormDataParam("image") InputStream uploadedInputStream,
@FormDataParam("image") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "e://game/" + fileDetail.getFileName();
boolean response=false;
// save it
try{
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
return response=true;
}catch(IOException e){
e.printStackTrace();
}
return response;
}
需要在Android端發送圖像(我在AsyncTask的doInBackground中完成)
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://"+ip+":8080/MiniJarvisFaceServer/image");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", new FileBody(file));
postRequest.setEntity(reqEntity);
ResponseHandler<String> handler = new BasicResponseHandler();
String response = httpClient.execute(postRequest,handler);
Log.d("Response", response);
httpClient.getConnectionManager().shutdown();
請按照本指南進行操作。它在服務器端使用PHP。我使用Android Studio和httpmime.4.3.6,並像魅力一樣工作 http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
它也支持視頻,它顯示瞭如何響應來自服務器的一些結果。唯一棘手的問題是確保您使用HttClient for Android和正確版本的HttpMime。現在HttpMime 4.4.x沒有工作,浪費了我一週的時間。使用4.3.6
- 1. 上傳圖片到網絡服務器
- 2. 網絡服務器發送圖片通過HTTP
- 3. C網絡服務器頭髮送
- 4. 將數據從android發送到網絡服務器
- 5. 如何發送多個圖像到網絡服務器
- 6. 從應用程序發送圖像到網絡服務器
- 7. Android發送圖像到網絡服務器
- 8. 發送圖像文件到網絡服務器
- 9. 使用Poco發送圖像到網絡服務器
- 10. 發送參數到網絡服務
- 11. 發送值到網絡服務 - BEGINNER
- 12. 無法將圖片上傳到網絡服務器
- 13. 如何將iphoto中的圖片上傳到網絡服務器?
- 14. 上傳圖片/照片從iPhone到網絡服務器(ASP.net)
- 15. XCode將圖像發送到服務器
- 16. Android將圖像發送到服務器
- 17. Ajax將圖像發送到服務器
- 18. 發送發佈數據到網絡服務器 - Android
- 19. Windows 8將圖像發佈到網絡服務器
- 20. iOS通過HTTP POST將圖片發送到服務器
- 21. 我們如何將圖片或照片上傳到ejabberd XMPP網絡服務器?
- 22. NowJs服務器到網絡服務器
- 23. 擴展iPhoto以將照片發佈到其他網絡服務?
- 24. 從JavaScript發送照片到服務器
- 25. 將生成的畫布圖像發送到網站服務器?
- 26. 如何將消息從Biztalk發送到許多網絡服務
- 27. 將會話ID從Android應用發送到Jersey網絡服務
- 28. Android,將值發送到ASP網絡服務
- 29. 200kb圖像base64無法發送到網絡服務
- 30. 發送數據包到網絡服務器?
可以指定服務器堆棧和可能的API嗎? – 2011-03-24 06:16:34
感謝您回覆,Ravi ...它是google apis 1.5,我不確定您的服務器堆棧是什麼意思...請問您能解釋一下嗎?我有點新的android .. – 2011-03-24 06:22:47
@Ravi:他沒有說任何異常。 – Mudassir 2011-03-24 06:26:03