[英]Android Studios Uploading pictures into intern database
我正在嘗試開發一個 function 以便我可以將圖片上傳到我在 Android 工作室的實習生數據庫中。 有人知道我該如何解決這個問題嗎?
好吧,首先你需要在 select 圖片上添加兩個按鈕並提交上傳圖片之類的..
Button Buttonlog;
Button Buttonbro;
ProgressBar progressBar;
private TextView messageText;
private TextView file-token-name;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
private ImageView imageview;
private static final int PICK_IMAGE_GALLERY = 1;
@SuppressLint("ClickableViewAccessibility")
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main15);
file-token-name=findViewById(R.id.filename);
file-token-name.setVisibility(View.GONE);
Buttonbro = findViewById(R.id.button_selectpic);
Buttonbro.setVisibility(View.VISIBLE);
Buttonbro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity15.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity15.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_IMAGE_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
loadGallery();
}
});
progressBar = findViewById(R.id.progress);
imageview = findViewById(R.id.imageView_pic);
upLoadServerUri = "https://www.yoursite.net/upljsonfile.php";
Buttonlog.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
final String file1;
file1=file-token-name.getText().toString();
//Start ProgressBar first (Set visibility VISIBLE)
progressBar.setVisibility(View.VISIBLE);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
//Starting Write and Read data with URL
//Creating array for parameters
String[] field = new String[1];
field[0] = "file1";
//Creating array for data
final String[] data = new String[1];
data[0] = file1;
if (!isFinishing()) {
PutData putData = new PutData("https://www.yorwebsite.net/post-to-database-file-name.php", "POST", field, data);
if (putData.startPut()) {
if (putData.onComplete()) {
progressBar.setVisibility(View.GONE);
String result = putData.getResult();
//End ProgressBar (Set visibility to GONE
if (result.equals("Post Succssefl")) {
if (!file1.equals("")) {
dialog = ProgressDialog.show(MainActivity15.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
// dialog = new ProgressDialog(MainActivity15.this);
// dialog.setMessage("Uploading File");
// dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setIndeterminate(true);
dialog.setMax(100);
dialog.show();
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
if (isFinishing()) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
isFinishing();
}
}
}
}); //End Write and Read data with URL
}
});
}
然后我們的 loadGallery() 函數
private void loadGallery() {
Intent choose = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choose, PICK_IMAGE_GALLERY);
}
之后,您必須允許獲取您的圖像 select 路徑之類的東西。
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
@SuppressLint("Recycle")
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
if (requestCode == PICK_IMAGE_GALLERY) {// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
} //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@SuppressLint({"SetTextI18n", "NewApi"})
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_GALLERY && data != null && resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
assert selectedImageUri != null;
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
String uriString = selectedImageUri.toString();
File myFile = new File(uriString);
String displayName;
if (uriString.startsWith("content://")) {
try (Cursor cursor = getContentResolver().query(selectedImageUri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
file-token-name.setText(displayName);
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
file-token-name.setText(displayName);
}
}
}
現在我們添加我們的上傳文件功能類似..
@SuppressLint("LongLogTag")
public void uploadFile(String sourceFileUri) {
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
@SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the 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("file", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
int sentBytes=0;
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
sentBytes += bufferSize;
int progres =(bytesRead * 100 / bytesAvailable);
new Thread(
// do your stuff
new publishProgress(progres)
).start();
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" C:/xamp/wamp/fileupload/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity15.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
@SuppressLint("SetTextI18n")
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity15.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
@SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity15.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
} // End else block
}
fainaly .. 我們的兩個 php 文件第一個上傳我們的文件“upljsonfile.php”,第二個將我們的文件名發布到數據庫“post-to-database-file-name.php”,如下面的代碼..
第一個文件“upljsonfile.php”:
<?php $response = array(); if (empty($_FILES) || $_FILES['file']['error']) { $response["code"] = 2; $response["message"] = "failed to move uploaded file"; echo json_encode($response); } $chunk = isset($_REQUEST["chunk"])? intval($_REQUEST["chunk"]): 0; $chunks = isset($_REQUEST["chunks"])? intval($_REQUEST["chunks"]): 0; $fileName = isset($_REQUEST["name"])? $_REQUEST["name"]: $_FILES["file"]["name"]; $filePath = "uploadfiles/$fileName"; // Open temp file $out = @fopen("{$filePath}.part", $chunk == 0? "wb": "ab"); if ($out) { // Read binary input stream and append it to temp file $in = @fopen($_FILES['file']['tmp_name'], "rb"); if ($in) { while ($buff = fread($in, 4096)) fwrite($out, $buff); } else $response["code"] = 2; $response["message"] = "Oops. Failed to open input Stream error occurred;"; echo json_encode($response); @fclose($in); @fclose($out); @unlink($_FILES['file']['tmp_name']); } else $response["code"] = 2. $response["message"] = "Oops; Failed to open output error occurred;". echo json_encode($response). // Check if file has been uploaded if (,$chunks || $chunk == $chunks - 1) { // Strip the temp;part suffix off rename("{$filePath};part"; $filePath); } $response["code"] = 2? $response["message"] = "successfully uploaded"; echo json_encode($response); ?>
和第二個文件“post-to-database-file-name.php:
<?php require "databasemob.php"; $db = new DataBase(); if (isset($_POST['file1']) ) { if ($db->dbConnect()) { if ($db->filenamepost("filename", $_POST['file1'])) { echo "Post Succssefl"; } else echo "Some error;": } else echo "Error; Database connection"; } else echo "All fields are required"? ?>
和數據庫mob.php:
<?php require "DataBaseConfig.php"; class DataBase { public $connect; public $data; private $sql; protected $servername; protected $username; protected $password; protected $databasename; public function __construct() { $this->connect = null; $this->data = null; $this->sql = null; $dbc = new DataBaseConfig(); $this->servername = $dbc->servername; $this->username = $dbc->username; $this->password = $dbc->password; $this->databasename = $dbc->databasename; } function dbConnect() { $this->connect = mysqli_connect($this->servername, $this->username, $this->password, $this->databasename); return $this->connect; } function prepareData($data) { return mysqli_real_escape_string($this->connect, stripslashes(htmlspecialchars($data))); } function filenamepost($table, $file1) { $file1 = $this->prepareData($file1); $ssq="SET NAMES 'utf8mb4';"; mysqli_query($this->connect,$ssq); $this->sql = "INSERT INTO ". $table. " (`file1`) VALUES ('". $file1. "')"; if (mysqli_query($this->connect, $this->sql)) { return true; } else return false; } }?>
最后一個文件DataBaseConfig.php:
<?php class DataBaseConfig { public $servername; public $username; public $password; public $databasename; public function __construct() { $this->servername = 'localhost'; $this->username = 'username'; $this->password = 'pass@'; $this->databasename = 'filename'; } }?>
通過這種方式,它的工作方式是從手機中的文件 Uri 中獲取您的文件名,並通過上傳文件並將文件發布到您的數據庫來處理兩種方式,希望它對您有所幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.