我正在制作一个演示应用程序,它将在MYSQL中存储值和图像,我的问题是我能够在数据库中上传图像但是当我尝试通过editText将用户名添加到提交按钮上的那个表时它会在Toast中提供< / p>
这是我的php文件
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$username = $_POST['username'];
require_once('dbConnect.php');
$sql = "INSERT INTO pic (image,username) VALUES ('$image','$username')";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$image,$username);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
这是我的Java文件MainActivity.jav
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btnChoose,btnSubmit;
private ImageView imageView;
public static final String UPLOAD_URL = "http://10.0.2.2/upload.php";
public static final String UPLOAD_KEY = "image";
public static final String TAG = "MY MESSAGE";
private int PICK_IMAGE_REQUEST = 1;
private Bitmap bitmap;
private EditText editUsername;
private Uri filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnChoose= (Button) findViewById(R.id.btnChoose);
btnSubmit= (Button) findViewById(R.id.btnSubmit);
imageView= (ImageView) findViewById(R.id.imageView);
editUsername= (EditText) findViewById(R.id.editUsername);
btnSubmit.setOnClickListener(this);
btnChoose.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnChoose:
showFileChooser();
break;
case R.id.btnSubmit:
uploadImage();
registerUser();
break;
}
}
private void uploadImage() {
class UploadImage extends AsyncTask<Bitmap,Void,String> {
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Uploading Image", "Please wait...",true,true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
String result = rh.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void registerUser(){
String username= editUsername.getText().toString().trim();
register(username);
}
private void register(String username) {
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RequestHandler ruc = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("username",params[0]);
String result = ruc.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
RegisterUser ru = new RegisterUser();
ru.execute(username);
}
}
这是我的RequestHandler.java类
public class RequestHandler {
public String sendGetRequest(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
StringBuilder sb = new StringBuilder();
while((result = bufferedReader.readLine())!=null){
sb.append(result);
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
这是我的activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.tejask.imageupload.MainActivity">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/string_choose_file"
android:id="@+id/btnChoose" />
<ImageView
android:layout_below="@id/btnChoose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/imageView" />
<EditText
android:layout_below="@id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editUsername"
android:hint="Username"
android:inputType="text"/>
<Button
android:layout_below="@id/editUsername"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/btnSubmit" />
</RelativeLayout>