图像未上传到服务器

时间:2018-01-16 07:54:31

标签: php android android-volley image-uploading

我正在处理应该具有将图像上传到服务器的功能的项目。在MainActivity中我有3个选项卡。第一个选项卡有2个按钮来捕获图像并从库中选择图像。选择或捕获图像后,将显示新的名为Upload活动的Activity。此上传活动包含1个图像视图和1个按钮上传图像。我能够在上传图片中显示图片但有问题。点击“上传”按钮后,响应来自服务器并且logcat中没有错误,我的图像仍未上传到服务器。

上传活动

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上传图像。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

加载页面https://smilestechno.000webhostapp.com/upload.php(通过GET)  结果

  

注意:未定义的索引:上传的文件   第4行/storage/ssd1/323/4193323/public_html/upload.php

     

注意:未定义的索引:上传的文件   第7行/storage/ssd1/323/4193323/public_html/upload.php

     

警告:copy():文件名不能为空   第7行上传/storage/ssd1/323/4193323/public_html/upload.php上传   失败

     

以下是一些调试信息:Array()

因此,您首先需要测试您正在处理POST请求并且已填充$_FILES数组。

要实际移动/保存使用move_uploaded_file而不是copy的文件,您应该通过测试error数组中的$_FILES值来测试上传是否成功。可以进行更多测试来确定文件扩展名,大小,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();
        }
    }
?>