图片没有上传到服务器
Image is not uploading to the server
我正在开发应该具有将图像上传到服务器的功能的项目。在 MainActivity 中,我有 3 个选项卡。第一个选项卡有 2 个按钮,用于从图库中捕获图像和 select 图像。在 select 拍摄或捕获图像后,将显示到名为上传 activity 的新 Activity。此上传 activity 有 1 个图像视图和 1 个按钮上传图像。我能够显示图像,但上传图像时出现问题。单击上传按钮后,来自服务器的响应没有错误 logcat 我的图像仍然没有上传到服务器。
上传Activity
public class Upload extends AppCompatActivity{
public static String URL = "https://smilestechno.000webhostapp.com/upload.php";
String filepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
final Button btnUpload = (Button) findViewById(R.id.btnUpload);
ImageView imageview = (ImageView) findViewById(R.id.imageview);
Intent intent = getIntent();
if (intent == null){
return;
}
final Uri imageUri = Uri.parse(intent.getStringExtra("image"));
filepath = getPath(Upload.this, imageUri);
imageview.setImageURI(imageUri);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (filepath != null){
imageUpload(filepath);
}else {
Toast.makeText(Upload.this, "Image not Selected", Toast.LENGTH_SHORT).show();
}
}
});
}
private void imageUpload(final String imagePath){
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(Upload.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(com.android.volley.error.VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
smr.addFile("img", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
public static String getPath(Context context, Uri contentUri) {
//copy file and send new file path
File TEMP_DIR_PATH = new File(Environment.getExternalStorageDirectory(), "/My Children/Temp");
TEMP_DIR_PATH.mkdir();
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName);
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
org.apache.commons.io.IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PHP 脚本
<?php
$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
echo "<p>";
if (copy($_FILES['uploadedfile']['tmp_name'], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
$servername = "localhost";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$filename="ImagesUpload/".$_FILES["uploadedfile"]["name"];
$sql = "INSERT INTO ImgInfo (ImgStatus, ImgLink,ImgUploadDate) VALUES ('0', '$filename',CURRENT_TIMESTAMP)";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else
{
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
我试过这个脚本。我创建了 html 页面,我可以使用此脚本从 html 上传图片。
IMO 你将错误的 key value
图像传递给 php
检查下面的代码
<?php
$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename($_FILES['img']['name']); //change here key as mentioned in java file.
echo "<p>";
if (copy($_FILES['img']['tmp_name'], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
$servername = "localhost";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$filename="ImagesUpload/".$_FILES["img"]["name"];
$sql = "INSERT INTO ImgInfo (ImgStatus, ImgLink,ImgUploadDate) VALUES ('0', '$filename',CURRENT_TIMESTAMP)";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else
{
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
或
保持你之前的 php 文件原样并使用 uploadedfile
而不是 img
在 imageUpload(final String imagePath)
中更改下面的代码
smr.addFile("uploadedfile", imagePath); //change key here.
MyApplication.getInstance().addToRequestQueue(smr);
正在加载页面 https://smilestechno.000webhostapp.com/upload.php(通过 GET)
结果
Notice: Undefined index: uploadedfile in
/storage/ssd1/323/4193323/public_html/upload.php on line 4
Notice: Undefined index: uploadedfile in
/storage/ssd1/323/4193323/public_html/upload.php on line 7
Warning: copy(): Filename cannot be empty in
/storage/ssd1/323/4193323/public_html/upload.php on line 7 Upload
failed
Here is some more debugging info:Array ( )
所以你首先需要测试你正在处理一个 POST 请求并且 $_FILES
数组已经被填充。
实际上 move/save 您使用 move_uploaded_file
而不是 copy
的文件,您应该通过测试 error
中的值来测试上传是否成功11=]数组。可以进行更多测试以确定文件扩展名、大小、MIME 类型等 - 所有这些都可以分叉处理。
下面使用准备好的语句来希望防止 sql 注入...
<?php
if( $_SERVER['REQUEST_METHOD']=='POST') && !empty( $_FILES['uploadedfile'] ) ){
try{
$obj=(object)$_FILES['uploadedfile'];
$name=$obj->name;
$size=$obj->size;
$tmp=$obj->tpm_name;
$type=$obj->type;
$error=$obj->error;
if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){
$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename( $name );
$status = move_uploaded_file( $tmp, $uploadfile );
if( $status ){
$servername = "localhost";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
$conn = new mysqli($servername, $username, $password, $dbname);
$filename="$uploaddir/$name";
$sql='insert into imginfo (imgstatus, imglink,imguploaddate) values ( '0', ?, CURRENT_TIMESTAMP )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bind_param('s',$filename);
$result=$stmt->execute();
$message=$result ? 'New record created successfully' : 'Upload failed';
/* you could also add this to display a message but generally better to redirect the user */
#throw new Exception( $message );
} else {
throw new Exception('failed to prepare sql');
}
} else {
throw new Exception('Failed to move file - check permissions');
}
} else {
throw new Exception('bad foo');
}
}catch( Exception $e ){
echo $e->getMessage();
}
}
?>
我正在开发应该具有将图像上传到服务器的功能的项目。在 MainActivity 中,我有 3 个选项卡。第一个选项卡有 2 个按钮,用于从图库中捕获图像和 select 图像。在 select 拍摄或捕获图像后,将显示到名为上传 activity 的新 Activity。此上传 activity 有 1 个图像视图和 1 个按钮上传图像。我能够显示图像,但上传图像时出现问题。单击上传按钮后,来自服务器的响应没有错误 logcat 我的图像仍然没有上传到服务器。
上传Activity
public class Upload extends AppCompatActivity{
public static String URL = "https://smilestechno.000webhostapp.com/upload.php";
String filepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
final Button btnUpload = (Button) findViewById(R.id.btnUpload);
ImageView imageview = (ImageView) findViewById(R.id.imageview);
Intent intent = getIntent();
if (intent == null){
return;
}
final Uri imageUri = Uri.parse(intent.getStringExtra("image"));
filepath = getPath(Upload.this, imageUri);
imageview.setImageURI(imageUri);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (filepath != null){
imageUpload(filepath);
}else {
Toast.makeText(Upload.this, "Image not Selected", Toast.LENGTH_SHORT).show();
}
}
});
}
private void imageUpload(final String imagePath){
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(Upload.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(com.android.volley.error.VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
smr.addFile("img", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
public static String getPath(Context context, Uri contentUri) {
//copy file and send new file path
File TEMP_DIR_PATH = new File(Environment.getExternalStorageDirectory(), "/My Children/Temp");
TEMP_DIR_PATH.mkdir();
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName);
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
org.apache.commons.io.IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PHP 脚本
<?php
$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
echo "<p>";
if (copy($_FILES['uploadedfile']['tmp_name'], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
$servername = "localhost";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$filename="ImagesUpload/".$_FILES["uploadedfile"]["name"];
$sql = "INSERT INTO ImgInfo (ImgStatus, ImgLink,ImgUploadDate) VALUES ('0', '$filename',CURRENT_TIMESTAMP)";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else
{
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
我试过这个脚本。我创建了 html 页面,我可以使用此脚本从 html 上传图片。
IMO 你将错误的 key value
图像传递给 php
检查下面的代码
<?php
$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename($_FILES['img']['name']); //change here key as mentioned in java file.
echo "<p>";
if (copy($_FILES['img']['tmp_name'], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
$servername = "localhost";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$filename="ImagesUpload/".$_FILES["img"]["name"];
$sql = "INSERT INTO ImgInfo (ImgStatus, ImgLink,ImgUploadDate) VALUES ('0', '$filename',CURRENT_TIMESTAMP)";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else
{
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
或
保持你之前的 php 文件原样并使用 uploadedfile
而不是 img
在 imageUpload(final String imagePath)
smr.addFile("uploadedfile", imagePath); //change key here.
MyApplication.getInstance().addToRequestQueue(smr);
正在加载页面 https://smilestechno.000webhostapp.com/upload.php(通过 GET) 结果
Notice: Undefined index: uploadedfile in /storage/ssd1/323/4193323/public_html/upload.php on line 4
Notice: Undefined index: uploadedfile in /storage/ssd1/323/4193323/public_html/upload.php on line 7
Warning: copy(): Filename cannot be empty in /storage/ssd1/323/4193323/public_html/upload.php on line 7 Upload failed
Here is some more debugging info:Array ( )
所以你首先需要测试你正在处理一个 POST 请求并且 $_FILES
数组已经被填充。
实际上 move/save 您使用 move_uploaded_file
而不是 copy
的文件,您应该通过测试 error
中的值来测试上传是否成功11=]数组。可以进行更多测试以确定文件扩展名、大小、MIME 类型等 - 所有这些都可以分叉处理。
下面使用准备好的语句来希望防止 sql 注入...
<?php
if( $_SERVER['REQUEST_METHOD']=='POST') && !empty( $_FILES['uploadedfile'] ) ){
try{
$obj=(object)$_FILES['uploadedfile'];
$name=$obj->name;
$size=$obj->size;
$tmp=$obj->tpm_name;
$type=$obj->type;
$error=$obj->error;
if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){
$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename( $name );
$status = move_uploaded_file( $tmp, $uploadfile );
if( $status ){
$servername = "localhost";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
$conn = new mysqli($servername, $username, $password, $dbname);
$filename="$uploaddir/$name";
$sql='insert into imginfo (imgstatus, imglink,imguploaddate) values ( '0', ?, CURRENT_TIMESTAMP )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bind_param('s',$filename);
$result=$stmt->execute();
$message=$result ? 'New record created successfully' : 'Upload failed';
/* you could also add this to display a message but generally better to redirect the user */
#throw new Exception( $message );
} else {
throw new Exception('failed to prepare sql');
}
} else {
throw new Exception('Failed to move file - check permissions');
}
} else {
throw new Exception('bad foo');
}
}catch( Exception $e ){
echo $e->getMessage();
}
}
?>