Android上传图片到服务器C#是一个常见的问题,本篇文章将介绍如何实现这一操作。我们将使用HttpURLConnection来上传图片,该类是Android中用于执行HTTP请求的类。在服务器端,我们将使用C#来处理上传的图片。此外,我们还将介绍如何使用Base64编码将图片转换为字符串。
Android端上传图片步骤
public class MainActivity extends AppCompatActivity { private Button chooseFileButton; private Button uploadButton;
private static final int REQUEST_CODE = 111;
private String filePath;
private String serverUrl = "http://your-server-url.com/upload-image.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseFileButton = (Button) findViewById(R.id.choose_file_button);
uploadButton = (Button) findViewById(R.id.upload_button);
chooseFileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
}
});
uploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (filePath != null) {
new UploadFileTask().execute();
} else {
Toast.makeText(MainActivity.this, "Please choose a file", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
filePath = getRealPathFromUri(uri);
Toast.makeText(MainActivity.this, filePath, Toast.LENGTH_SHORT).show();
}
}
private String getRealPathFromUri(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(columnIndex);
cursor.close();
return path;
}
private class UploadFileTask extends AsyncTask {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
}
上一篇:android上传数据到数据库中