Java 将图片上传到服务器
我正在使用以下代码: 它起作用了 我想知道我要发送的照片是几秒钟前用相机拍的。 所以我创建了一个简单的方法来拍照,然后在活动结果上显示:Java 将图片上传到服务器,java,android,image,upload,camera,Java,Android,Image,Upload,Camera,我正在使用以下代码: 它起作用了 我想知道我要发送的照片是几秒钟前用相机拍的。 所以我创建了一个简单的方法来拍照,然后在活动结果上显示: protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST) { //2 Bitmap thumbnail = (Bitmap) data.ge
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的对象作为回报 您应该使用多部分实体
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();
其中selectedImage是图像的路径。@Alex编辑了答案