我使用此代码将文件上传到服务器:(如果我正确理解你的问题)
首先选择文件
在选择图像按钮侦听器中运行此方法之一:
从图库中选择照片:
void startImagePicker() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_SEND_IMAGE);
}
用相机拍照:
void startPhotoTaker() {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "cs_" + new Date().getTime() + ".jpg");
mLastPhoto = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mLastPhoto);
// start the image capture Intent
startActivityForResult(intent, REQUEST_TAKE_PICTURE);
}
从文件管理器中选择任何文件:
void startFilePicker() {
Intent selectFile = new Intent(Intent.ACTION_GET_CONTENT);
selectFile.setType("file/*");
Intent intentChooser = Intent.createChooser(selectFile, "Select File");
if (intentChooser != null)
startActivityForResult(Intent.createChooser(selectFile, "Select File"), REQUEST_SEND_FILE);
}
在您的 onActivityForResault 方法中复制以下内容:
在 onActivityResult 中:
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SEND_IMAGE) {
Uri uri = resultIntent.getData();
if (uri == null) {
return;
}
File file = new File(getRealPathFromURI(uri));
final Handler handler = new Handler();
MediaScannerConnection.scanFile(
this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, final Uri uri) {
handler.post(new Runnable() {
@Override
public void run() {
uploadFile(uri);
}
});
}
});
} else if (requestCode == REQUEST_SEND_FILE |) {
Uri uri = resultIntent.getData();
if (uri == null) {
return;
}
uploadFile(uri);
} else if (requestCode == REQUEST_TAKE_PICTURE) {
File file = new File(getRealPathFromURI(mLastPhoto));
final Handler handler = new Handler();
MediaScannerConnection.scanFile(
this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, final Uri uri) {
handler.post(new Runnable() {
@Override
public void run() {
uploadFile(mLastPhoto);
}
});
}
});
}
}
上传文件到服务器:
private String uploadFile(Uri resourceUri) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
final File sourceFile = new File(getRealPathFromURI(resourceUri));
String serverResponseMessage = null;
String responce = null;
if (!sourceFile.isFile()) {
dialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "File not found !", Toast.LENGTH_LONG).show();
}
});
return "no file";
} else {
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile.getPath());
URL url = new URL("your upload server/API url");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty(POST_FIELD, sourceFile.getName());
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + POST_FIELD + "\";filename="
+ sourceFile.getName() + 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 serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode <= 200) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PreviewActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PreviewActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PreviewActivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
}
dialog.dismiss();
return responce;
}