【问题标题】:Image is not uploading to the server图片未上传到服务器
【发布时间】:2018-06-24 21:01:29
【问题描述】:

我正在开发应该具有将图像上传到服务器的功能的项目。在 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 上传图像。

【问题讨论】:

标签: php android android-volley image-uploading


【解决方案1】:

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 而不是 imgimageUpload(final String imagePath) 中更改以下代码

  smr.addFile("uploadedfile", imagePath); //change key here.
     MyApplication.getInstance().addToRequestQueue(smr);

【讨论】:

  • 请说明您所做的更改。
  • 我不是 OP。 ;)
  • @Akintunde007 哎呀对不起!已删除的消息希望您能得到我所做的更改...
【解决方案2】:

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

注意:未定义索引:uploadfile in /storage/ssd1/323/4193323/public_html/upload.php 在第 4 行

注意:未定义索引:uploadfile in /storage/ssd1/323/4193323/public_html/upload.php 在第 7 行

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

这里还有一些调试信息:Array()

所以你首先需要测试你正在处理一个 POST 请求并且$_FILES 数组已经被填充。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    相关资源
    最近更新 更多