[英]Storing the image in folder with unique name and path in database
我通過json獲取php文件中的圖片編碼數據。 我的要求是將該圖像存儲在服務器中的一個文件夾中,前提是每個圖像都應分配一個唯一的名稱。 我對如何將圖像存儲在具有唯一名稱的文件夾中然后再次將圖像的路徑存儲在數據庫中產生了很多疑問。 我看過幾個 StackOverflow 問題和在線資源,但無法清楚地了解它們。 對於從事 PHP 工作的人來說,這個問題似乎很簡單。 但作為 php 新手和 Android 開發人員,我無法理解那些不太詳細的答案。 因此,如果有人可以幫助我提供代碼片段和解釋,我將不勝感激。 我盡量保持我對問題和代碼的解釋和注釋的清晰。 如果有任何錯誤,請放輕松。以下是我嘗試並在某些地方卡住的代碼。 提前致謝..
<?php
$response = array();
// check for required fields
if (isset($_POST['mailid']) && isset($_POST['category']) && isset($_POST['description']) && isset($_POST['contactNum']) && isset($_POST['lookingto']) && isset($_POST['image'])) {
$usermail = $_POST['mailid'];
$category = $_POST['category'];
$description = $_POST['description'];
$contactNum = $_POST['contactNum'];
$lookingto = $_POST['lookingto'];
$base=$_POST['image'];
$binary=base64_decode($base);
$folder = "images/"; // This is my folder "images" in which pics have to be stored.
$file = fopen('storepic.jpg', 'wb'); // Here I have to give name dynamically to each pic provided that should be unique. Here I mentioned pic name as storepic.jpg, a static name.
fwrite($file, $binary);
fclose($file);
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO details(usermail, category, description, contactnumber,posting_for) VALUES('$usermail', '$category', '$description','$contactNum','$lookingto')");
//// Even after giving dynamic name how can we store the path of the dynamic named image into database in the above query. For that what should be done here..
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
// echoing JSON response
echo json_encode($response);
}
} else {
$response["success"] = 0;
// echoing JSON response
echo json_encode($response);
}
?>
即使在其他 php 文件中,我也通過選擇查詢檢索數據。 我能夠獲得我插入的正常數據,可以在 Android 客戶端應用程序上獲得它。 但是又如何從路徑中獲取圖像以便稍后轉換為 base64 編碼數據,然后作為 json 響應回顯..
注意:-我的用戶界面不是表單。 這是一個Android用戶界面..
// A very basic field validation. You should really use mysqli* or PDO*.
$fields = array(
'usermail' => 'mailid',
'category' => 'category',
'description' => 'description',
'contactNum' => 'contactNum',
'lookingto' => 'lookingto',
'binary' => 'base',
);
$okay = true;
foreach($fields as $var => $field)
{
if (!isset($_POST[$field]))
$okay = false;
if ('binary' == $var)
${$var} = base64_decode($_POST[$field]);
else
${$var} = mysql_real_escape_string($_POST[$field]);
}
if (!$okay)
{
$response["success"] = 0;
Header("Content-Type: application/json;charset=UTF-8");
die(json_encode($response));
}
$folder = "images/"; // This is my folder "images" in which pics have to be stored.
$file = tempnam($folder, 'image');
$fp = fopen($file, 'w');
fwrite($file, $binary);
fclose($file);
/* BUT WHAT IF THE FILE IS NOT JPEG?
Then you use GD library and do:
$gd = ImageCreateFromString($binary);
if (!$gd)
{
// Abort. Image was invalid.
}
// Here you can even resize it.
ImageJPEG($gd, $file, 75); // Quality 75%; useable values from 40 to 100
ImageDestroy($gd);
*/
...
$result = mysql_query("INSERT INTO details(usermail, category, description, contactnumber,posting_for) VALUES('$usermail', '$category', '$description','$contactNum','$lookingto')");
// I assume that the above table has an unique ID. So we retrieve it
$lastid = mysql_insert_id();
rename($file, $newfile = sprintf("%s/img%08d.jpg", $folder, $lastid));
上面,您不需要文件名的列名,因為名稱與行 ID 相同:如果 ID 為 1234,則圖像為images/img00001234.jpg
。
否則,您必須發出另一個查詢:
UPDATE details SET filename='$newfile' WHERE id = $lastid;
在所有情況下,您都會收到有關要檢索的行的一些信息; 至少它的 ID,或者無論如何你可以插入WHERE
一些條件。 例如,如果您收到用戶電子郵件(並且它是一個唯一鍵),您將使用WHERE email='...'
。
因此,您將能夠發出SELECT * FROM details WHERE...
並且在這些詳細信息中,您將找到 ID 或filename
段。
在第一種情況下,您已經足夠構建文件名,甚至不需要數據庫查詢,但請記住,任何知道 ID 的人現在都可以訪問圖像,這可能是無害的甚至是需要的(例如用戶公共頭像圖像)但是有時可能不是。
$lastid = (int)$_REQUEST['id'];
$newfile = sprintf("%s/img%08d.jpg", $folder, $lastid);
注意語法和上面一樣; (int)
cast 是要記住這是用戶提供的信息,可能包含各種惡意 crud。
在第二種情況下,您將發出WHERE
並從檢索到的元組中獲取 ID 或直接獲取文件名字段。
擁有圖像路徑,您可以將其發送給用戶......如果圖像在那里。 只是檢查。
if (!is_readable($newfile))
{
Header('HTTP/1.0 404 Not Found')
readfile('/path/to/beautiful/error-page.html');
die();
}
// if you are really paranoid, or want to support different quality images,
// you can $gd = imageCreateFromJPEG($newfile); here, check it succeeded or
// send 404 / 500 error if it failed, manipulate $gd and send it along with
// ImageJPEG($gd, '', $quality); instead of the readfile() down there. With
// this approach, you'll better not send Content-Length, though. This makes
// image DOWNLOADS more awkward (you don't see "104K of 1.3M downloaded").
Header('Content-Type: image/jpeg');
Header('Content-Length: ' . filesize($newfile));
readfile($newfile);
die();
......就是這樣。 在調用上面的 HTML 源代碼中,您可能有:
<img class="avatar" src="images.php?id=<?php echo $details['id']; ?>" />
(當然,生成 HTML 的 PHP需要訪問數據庫並獲取$details
)。
還有其他設置允許“調用”PHP 以受保護的方式將數據庫元組信息保存在 _GET 參數中,這樣即使用戶看到圖像是用
image.php?id=1234
並且知道Bob的ID是7654,但她還是無法通過將1234更改為7654來檢索圖像,但我不知道這是否有人感興趣。
對於 Web 瀏覽器,設置內容就足夠了。 使用 Internet Explorer,您可能需要文件以.jpg
結尾,而這反過來可能需要使用 URL 重寫方案。
package com.example.test_image_save;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
protected static TextView textView;
protected static ImageView image1, image2;
protected Button get_image, save_image, read_image;
private String selectedImagePath;
private static final int SELECT_PICTURE = 1;
String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
String TABLE_NAME = "mytable";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image1 = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2);
textView = (TextView) findViewById(R.id.textView1);
get_image = (Button) findViewById(R.id.get_image);
get_image.setOnClickListener(this);
save_image = (Button) findViewById(R.id.save_image);
save_image.setOnClickListener(this);
read_image = (Button) findViewById(R.id.read_image);
read_image.setOnClickListener(this);
}
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.get_image:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
break;
case R.id.save_image:
createTable();
saveInDB();
break;
case R.id.read_image:
readFromDB();
break;
default:
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
image1.setVisibility(View.VISIBLE);
image1.setImageURI(selectedImageUri);
}
}
}
@SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
void createTable() {
SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
Context.MODE_PRIVATE, null);
String MySQL = "create table if not exists "
+ TABLE_NAME
+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
myDb.execSQL(MySQL);
myDb.close();
}
void saveInDB() {
SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
Context.MODE_PRIVATE, null);
byte[] byteImage1 = null;
String s = myDb.getPath();
myDb.execSQL("delete from " + TABLE_NAME); // clearing the table
ContentValues newValues = new ContentValues();
String name = "SachinImages";
newValues.put("name", name);
try {
FileInputStream instream = new FileInputStream(selectedImagePath);
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
newValues.put("image", byteImage1);
long ret = myDb.insert(TABLE_NAME, null, newValues);
if (ret < 0)
textView.append("Error");
} catch (IOException e) {
textView.append("Error Exception : " + e.getMessage());
}
myDb.close();
textView.append("\n Saving Details \n Name : " + name);
textView.append("\n Image Size : " + byteImage1.length + " KB");
textView.append("\n Saved in DB : " + s + "\n");
Toast.makeText(this.getBaseContext(),
"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
}
void readFromDB() {
byte[] byteImage2 = null;
SQLiteDatabase myDb;
myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
textView.append("\n Reading Details \n Name : " + cur.getString(1));
cur.moveToNext();
}
// /////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
setImage(byteImage2);
cur.close();
myDb.close();
Toast.makeText(this.getBaseContext(),
"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
Toast.makeText(this.getBaseContext(),
"If your image is big, please scrolldown to see the result.",
Toast.LENGTH_SHORT).show();
}
void setImage(byte[] byteImage2) {
image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
byteImage2.length));
textView.append("\n Image Size : " + byteImage2.length + " KB");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.