任何人都可以使用带有user_id的登录网络服务帮助我 如何将图像,文本和视频 上传到数据库并上传到MySql数据库 这是我的代码。 PHP文件:
<?php
require '../db_connect.php';
if (isset($_POST['message']))
{
$message=$_POST['message'];
$user_id=$_POST['user_id'];
//$user_id=1;
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$query=mysqli_query($con,"INSERT INTO posts(user_id,post_description,is_active,created_at) values('".$user_id."','".$message."',1,'".$date."')");
if($query){
$i_post_id = mysqli_insert_id($con);
if(isset($_POST['img_file'])){
$sourcePath = $_POST['img_file'];
// create dir if not exists
if(!is_dir('../img/Post')){
mkdir('../img/Post',0777,true);
}
$s_file_name = time()."_".$_POST['img_file'];
$targetPath = "../img/Post/".$s_file_name;
if(move_uploaded_file($sourcePath,$targetPath)) {
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
$source_img = $targetPath;
if(!is_dir('../img/Post/compress')){
mkdir('../img/Post/compress');
}
$destination_img = '../img/Post/compress/'.$s_file_name;
$d = compress($source_img, $destination_img, 50);
$i_file_type = 1; // 1 for image.
$query=mysqli_query($con,"INSERT INTO post_files(post_id,file_name,file_type,is_active) values('".$i_post_id."','".$s_file_name."',$i_file_type,1)");
}
}
if(isset($_POST['video_file'])){
//echo "in";
$sourcePath = $_POST['video_file'];
// create dir if not exists
if(!is_dir('../img/Post')){
mkdir('../img/Post',0777,true);
}
$s_file_name = time()."_".pathinfo($_POST['video_file'], PATHINFO_FILENAME).".mp4";
$s_file_name = str_replace(' ', '_', $s_file_name);
$targetPath = "../img/Post/convert/".$s_file_name;
if(!is_dir('../img/Post/convert')){
mkdir('../img/Post/convert',0777,true);
}
$s_post_path = dirname(__FILE__).'/';
$handbrake = "HandBrake/HandBrakeCLI";
$cmd = $s_post_path.$handbrake." -i ".$sourcePath." -o ".$s_post_path.$targetPath." -e x264 -q 25 -r 15 -B 64 -X 480 -O";
passthru($cmd,$err);
$i_file_type = 2; // 2 for video.
$query=mysqli_query($con,"INSERT INTO post_files(post_id,file_name,file_type,is_active) values('".$i_post_id."','".$s_file_name."',$i_file_type,1)");
}
$response["success"] = 1;
$response["message"] = "Post successfully added.";
// echoing JSON response
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
?>
ANDROID CODE:
public class Posts_DATA extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = Posts_DATA.class.getSimpleName();
EmojiconEditText emojiconEditText;
EmojiconTextView textView;
ImageView emojiImageView;
ImageView submitButton;
View rootView;
EmojIconActions emojIcon;
private TextView buttonChoose;
private TextView buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL = "http://app-1494216827.000webhostapp.com/register_sample/images/upload.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.posts_data);
rootView = findViewById(R.id.root_view);
emojiImageView = (ImageView) findViewById(R.id.emoji_btn);
submitButton = (ImageView) findViewById(R.id.submit_btn);
emojiconEditText = (EmojiconEditText) findViewById(R.id.emojicon_edit_text);
emojIcon = new EmojIconActions(this, rootView, emojiconEditText, emojiImageView);
emojIcon.ShowEmojIcon();
emojIcon.setIconsIds(R.drawable.ic_action_keyboard, R.drawable.smiley);
emojIcon.setKeyboardListener(new EmojIconActions.KeyboardListener() {
@Override
public void onKeyboardOpen() {
Log.e(TAG, "Keyboard opened!");
}
@Override
public void onKeyboardClose() {
Log.e(TAG, "Keyboard closed");
}
});
buttonChoose = (TextView) findViewById(R.id.post_image);
buttonUpload = (TextView) findViewById(R.id.buttonUpload);
editTextName = (EditText) findViewById(R.id.post_desc);
imageView = (ImageView) findViewById(R.id.posting_imageview_display);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
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 uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(Posts_DATA.this, s, Toast.LENGTH_LONG).show();
finish();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(Posts_DATA.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = emojiconEditText.getText().toString().trim();
byte[] data = new byte[0];
try {
data = emojiconEditText.getText().toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
name = Base64.encodeToString(data, Base64.DEFAULT);
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
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) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
bitmap = Bitmap.createScaledBitmap(bitmap, 200, 300, true);
imageView.setMaxWidth(200);
imageView.setMaxHeight(300);
imageView.setVisibility(View.VISIBLE);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
}
}
登录JAVA CLASS:
public class NewLogin extends ActionBarActivity {
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
public static final String USER_NAME = "USERNAME";
String username;
String password;
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
class loginAccess extends AsyncTask<String, String, String> {
String access;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
@Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String url = "";
JSONObject json = null;
int successValue = 0;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("TESS :: ", json.toString());
successValue = json.getInt("success");
//Log.d("Success Response :: ", String.valueOf(successValue));
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return String.valueOf(successValue);
}
protected void onPostExecute(String jsonstring) {
pDialog.dismiss();
if(jsonstring.equals("1")){
Intent i = new Intent(NewLogin.this, Sample.class);
startActivity(i);
}else{
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
}
}
}