android 拍照上传 源代码
时间: 2023-05-16 10:03:39 浏览: 167
Android拍照上传主要分为两个部分,即照相和上传。在照相方面需要使用Android提供的API,如Camera类来实现;而在上传方面则可以使用HTTP POST请求或其他方式实现,如FTP的方式上传。以下是一个简单的拍照上传的源代码:
```
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView mImageView;
private Bitmap mBitmap;
private String mFilePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
Button captureButton = findViewById(R.id.captureButton);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
Button uploadButton = findViewById(R.id.uploadButton);
uploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UploadTask uploadTask = new UploadTask();
uploadTask.execute(mFilePath);
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mFilePath = image.getAbsolutePath();
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
mBitmap = BitmapFactory.decodeFile(mFilePath);
mImageView.setImageBitmap(mBitmap);
}
}
private class UploadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String filePath = params[0];
HttpsURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(filePath);
if(!sourceFile.isFile()){
return null;
}
try{
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://example.com/upload.php");
conn = (HttpsURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
return "success";
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if(result != null && result.equals("success")){
Toast.makeText(MainActivity.this, "Upload Success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}
}
}
```
上述代码中,setOnClickListener()方法可以监听拍照和上传按钮的点击事件,dispatchTakePictureIntent()方法用于调用系统相机拍照,createImageFile()方法用于创建保存拍照图片的文件,而HTTP POST上传的实现则在UploadTask类中的doInBackground()方法中。当上传成功或失败时会通过Toast提示用户。
阅读全文