【发布时间】:2011-05-27 08:55:11
【问题描述】:
在我的应用程序中,我试图从我的设备捕获图像,并且我想将其上传到服务器。 我正在关注here
发布的答案以下是我启动相机的代码
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startCamera();
}
});
}
public void startCamera()
{
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, 0 );
}
但是在我捕获并尝试上传后,它会崩溃。在 logcat 它显示错误 在 OnActivity 结果 和 doFileUpload
以下是我的代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch( resultCode )
{
case 0:
break;
case -1:
onPhotoTaken();
break;
}
}
protected void onPhotoTaken()
{
doFileUpload(MediaStore.EXTRA_OUTPUT);
}
private void doFileUpload(String extraOutput)
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inStream = null;
String urlServer = "http:XXXXXXXXXXXXXXXXXXXXXX/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
FileInputStream fileInputStream = new FileInputStream(new File(extraOutput) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new
DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" + extraOutput +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens +lineEnd);
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
请帮我解决我的错误......请
【问题讨论】:
-
你必须更具体。 LogCat 中显示什么样的错误?
-
除此之外:你不应该在 UI Thread 中进行网络操作,这是一个很大的禁忌。
-
@Siva K:能给我完整的代码吗?
-
@Nirav Ranpara - 你的问题是什么,给我发邮件(sivasankarkb@gmail.com),我会帮你
-
@Nirav Ranpara - 抱歉回复晚了......