上传图片到服务器
问题描述:
我使用下面的代码: http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106上传图片到服务器
IT WORKS!
我想知道我将发送的图片是几秒钟前用相机拍摄的图片。 所以..我创建了一个简单的方法来拍摄照片,然后这个OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
//3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "guasto.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
uploadFile(uploadFilePath + "" + uploadFileName); //this should call the working method to upload the picture
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
的问题是,上传不了,它正确执行这行代码之前停止:
dos = new DataOutputStream(conn.getOutputStream());
我该怎么办才能解决问题......? 非常感谢你
答
尝试以下代码。创建一个异步任务并在doInBackground方法中添加代码。你将得到InputStream的对象。
您应该使用Multipart实体。
File file = new File(selectedImage);
ContentBody cbFile = new FileBody(file, "image/*");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(RequestParams.POST, cbFile);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://yourwebserveraddress.com/apiname_or_whatever_path_it_is");
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
Where selectedImage是图像的路径。
@Alex编辑答案 – 2014-09-29 09:45:28