gpt4 book ai didi

java - Android数据post到Mysql的方法

转载 作者:搜寻专家 更新时间:2023-11-01 09:47:30 26 4
gpt4 key购买 nike

<分区>

我有一个 android 应用程序,您可以在登录后上传视频。我正在尝试跟踪用户并在他们上传视频时插入 mysql 查询。所以基本上,当用户上传视频时,我如何将用户名发布到 PHP 文件?

上传.java

public class Upload {

public static final String UPLOAD_URL= "mylinkishere.com/upload.php";

private int serverResponseCode;

public String uploadVideo(String file) {

String fileName = file;
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;

File sourceFile = new File(file);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return null;
}

try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(UPLOAD_URL);
conn = (HttpURLConnection) 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);
conn.setRequestProperty("myFile", fileName);
dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();
Log.i("Huzza", "Initial .available : " + bytesAvailable);

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);

serverResponseCode = conn.getResponseCode();

fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

if (serverResponseCode == 200) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException ioex) {
}
return sb.toString();
}else {
return "Could not upload";
}
}

MainActivity.Java

    package net.simplifiedcoding.androidloginlogout;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {

private Button buttonChoose;
private Button buttonUpload;
private TextView textView2;
private TextView edtTc;
private TextView textViewResponse;

private static final int SELECT_VIDEO = 3;

private String selectedPath;

@Override
protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);

SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"Not Available");

//Showing the current logged in email to textview
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);

textView = (TextView) findViewById(R.id.textView);
textViewResponse = (TextView) findViewById(R.id.textViewResponse);

buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}

private void chooseVideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Video Seçin "), SELECT_VIDEO);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO) {
System.out.println("SELECT_VIDEO");
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
textView.setText(selectedPath);
}
}
}

public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();

cursor = getContentResolver().query(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
cursor.close();

return path;
}

private void uploadVideo() {
class UploadVideo extends AsyncTask<Void, Void, String> {

ProgressDialog uploading;

@Override
protected void onPreExecute() {
super.onPreExecute();
uploading = ProgressDialog.show(ProfileActivity.this, "Yükleniyor", "Lütfen bekleyin...", false, false);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
uploading.dismiss();
textViewResponse.setText(Html.fromHtml("<b>Yüklendi: <a href='" + s + "'>" + s + "</a></b>"));
textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
}

@Override
protected String doInBackground(Void... params) {
Upload u = new Upload();
String msg = u.uploadVideo(selectedPath);
return msg;
}
}
UploadVideo uv = new UploadVideo();
uv.execute();
}


@Override
public void onClick(View v) {
if (v == buttonChoose) {
chooseVideo();
}
if (v == buttonUpload) {
uploadVideo();
}
}

//Textview to show currently logged in user
private TextView textView;

//Logout function
private void logout(){
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Çıkış yapmak mı istiyorsunuz?");
alertDialogBuilder.setPositiveButton("Evet",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {

//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();

//Puting the value false for loggedin
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);

//Putting blank value to email
editor.putString(Config.EMAIL_SHARED_PREF, "");

//Saving the sharedpreferences
editor.commit();

//Starting login activity
Intent intent = new Intent(ProfileActivity.this, LoginActivity.class);
startActivity(intent);
}
});

alertDialogBuilder.setNegativeButton("Hayır",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {

}
});

//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menuLogout) {
logout();
}
return super.onOptionsItemSelected(item);
}

我的upload.php文件

if($_SERVER['REQUEST_METHOD']=='POST'){
$file_name = $_FILES['myFile']['name'];
$file_size = $_FILES['myFile']['size'];
$file_type = $_FILES['myFile']['type'];
$temp_name = $_FILES['myFile']['tmp_name'];

$location = "uploads/";

move_uploaded_file($temp_name, $location.$file_name);
echo "mylink.com/video/uploads/".$file_name;
}else{
echo "Error";
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com