使用截击上传pdf,但在服务器文件夹中获取空文件 [英] uploading a pdf using volley but gets null file on server folder

查看:62
本文介绍了使用截击上传pdf,但在服务器文件夹中获取空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用volley库在主机托管人域上的数据库以及同一主机托管人域中的文件夹中上载pdf文件

I am uploading a pdf file using volley library in database on hostinger domain and also in folder on same hostinger domain

这是我的xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/colorAccent"
tools:context="com.example.singhharpal.fileupload_apr26.MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="18sp"
    android:id="@+id/tvHeading"
    android:text="Touch the icon below to upload file to server"
    android:textColor="#fff"
    android:textStyle="bold"/>
<Button
    android:id="@+id/ivAttachment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CHoose"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>

<TextView
    android:id="@+id/tv_file_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#fff"
    android:layout_marginTop="10dp"
    android:gravity="center"
    android:layout_below="@+id/ivAttachment"
    android:layout_centerHorizontal="true"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/b_upload"
    android:text="Upload"
    android:textStyle="bold"
    android:textSize="20sp"
    android:layout_alignParentBottom="true"
    android:gravity="center"
    android:textColor="#fff"
    android:background="#039be5"/>

我的Java文件

package com.example.singhharpal.fileupload_apr26;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
//import com.squareup.picasso.Picasso;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements     view.OnClickListener
{
private Button buttonClick;
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
File file;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 200;
String filename;
String s1,s2;
private String UPLOAD_URL ="http://harpal-projects.16mb.com/sbbs/php/file-upload2.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "fname";
private String KEY_ROLL = "roll_no";


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
/*
    Button textView = (TextView) findViewById(R.id.userName);
    TextView t1 = (TextView) findViewById(R.id.textView4);
    TextView t2 = (TextView) findViewById(R.id.textView5);
*/

   /*// SharedPreferences sharedPreferences=getActivity().getSharedPreferences("userInfo",getActivity().MODE_PRIVATE);       //my settings is file name

    s1=sharedPreferences.getString("username","");
    s2=sharedPreferences.getString("password","");
    t1.setText(s1);
    t2.setText(s2);*/

    //textView.setText("Welcome User " + intent.getStringExtra(RegisterStudent.KEY_USERNAME));
    buttonChoose = (Button)findViewById(R.id.ivAttachment);
    //buttonClick = (Button)findViewById(R.id.clickPic);
    buttonUpload = (Button)findViewById(R.id.b_upload);
    //imageView  = (ImageView)findViewById(R.id.imageView);

    buttonChoose.setOnClickListener(this);
    buttonUpload.setOnClickListener(this);
}

@Override
public void onClick(View v)
{
    if(v == buttonChoose)
    {
        showFileChooser();
    }
    if(v == buttonUpload)
    {
        uploadImage();
    }
}

private void showFileChooser()
{
    Intent intent = new Intent();
    intent.setType("application/pdf");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select File"), PICK_IMAGE_REQUEST);

    /*Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("image*//*;application/pdf");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    // special intent for Samsung file manager
    Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA_MULTIPLE");
    // if you want any file type, you can skip next line
    sIntent.putExtra("CONTENT_TYPE", "application/pdf");
    sIntent.addCategory(Intent.CATEGORY_DEFAULT);

    Intent chooserIntent;
    if (getPackageManager().resolveActivity(sIntent, 0) != null)
    {
        // it is device with samsung file manager
        chooserIntent = Intent.createChooser(sIntent, "Open file");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
    }
    else
    {
        chooserIntent = Intent.createChooser(intent, "Open file");
    }


    startActivityForResult(chooserIntent, 100);*/
}

@Override
public 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();
        Toast.makeText(MainActivity.this, ""+filePath, Toast.LENGTH_SHORT).show();

        filename=filePath.getLastPathSegment();
        Toast.makeText(MainActivity.this, ""+filename, Toast.LENGTH_SHORT).show();

            file = new File(filePath.toString());
            getStringFile(file);

    }
}

public String getStringFile(File f)
{
    StringBuilder sb = new StringBuilder();
    try
    {
        FileInputStream fileInputStream = new FileInputStream(file);

        BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));

        String line ;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line).append("\n");
            reader.close();
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return sb.toString();
}

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(getBaseContext(), s, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();
                    //Showing toast
                    Toast.makeText(getBaseContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String doc = getStringFile(file);

            //Getting Image Name
            //Creating parameters
            Map<String,String> params = new Hashtable<String, String>();

            //Adding parameters
            params.put("file", doc);
            params.put("fname", filename);



            //returning parameters
            return params;
        }
    };
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(){
                                     @Override
                                     public int getCurrentTimeout() {
                                         return 50000;
                                     }

                                     @Override
                                     public int getCurrentRetryCount() {
                                         return 50000;
                                     }

                                     @Override
                                     public void retry(VolleyError error) throws VolleyError {

                                     }
                                 }
    );

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());

    //Adding request to the queue
    requestQueue.add(stringRequest);

}
}  

我使用了php服务器脚本,在其中添加了一个查询以将文件插入到我的数据库文件夹和名为uploads的服务器文件夹中

I used php server script where i added a query to insert file into my database folder and in server folder named uploads

这是我的php脚本

<?php
 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

$file = $_POST['file'];
$fname = $_POST['fname'];

$file_path = "uploads/";
$actualpath = "http://harpal-projects.16mb.com/sbbs$file_path";

 $sql = "INSERT INTO files (file,fname) VALUES ('$actualpath','$fname') ";

 if(mysqli_query($con,$sql))
 {
             file_put_contents($file_path,base64_decode($file));

        echo "success";

 }else{
        echo "fail";
    }
?>  

我不知道我在哪里遇到问题,因为文件正在进入数据库表以及服务器的文件夹中,但是它的大小为0,即为null,所以没有用...告诉我如何修改此代码.??

I dont know where i am getting problme as file is going into database table and also in folder in my server but it's size is 0 i.e. it is null so it is of no use ... tell me how to modify this code.??

我尝试了convertFileToBase64String,但它也获取了空文件
在activtyonresult中,我尝试了此代码

I tried convertFileToBase64String but it gets null file too
in activtyonresult i tried this code

if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
    {
        Uri filePath = data.getData();
        Toast.makeText(MainActivity.this, ""+filePath, Toast.LENGTH_SHORT).show();

        filename=filePath.getLastPathSegment();
        Toast.makeText(MainActivity.this, ""+filename, Toast.LENGTH_LONG).show();

            file = new File(filePath.toString());

        try {
            FileInputStream fileInputStreamReader = new FileInputStream(file);
            byte[] bytes = new byte[(int)file.length()];
            fileInputStreamReader.read(bytes);
            encodedBase64 = new String(Base64.encodeBase64(bytes));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
           // doc=getStringFile(file);
        //Toast.makeText(MainActivity.this, ""+doc.length(), Toast.LENGTH_SHORT).show();

    }  

我用它来上传文件

params.put("file", encodedBase64);  

,当我用烤面包来看看encodedBase64的长度时,结果为0,与'file','fileinputreader','bytes'相同.
所以我认为这是不对的,或者可能是我错了..纠正我

and when i used toast to see lenght of encodedBase64 it results 0 , same for 'file','fileinputreader','bytes'
so i think it is not right or may be i am wrong..correct me

我尝试了这段代码,但它的值为空....好像我没有选择任何文件,或者文件在某处迷路了...

i tried this code but it gets null value....as if i didnt pick any file or the fle get lost there somewhere...

 public String convertFileToBase64String(File f) throws FileNotFoundException
{
    InputStream inputStream = new FileInputStream(f.getAbsolutePath());
    byte[] bytes;
    byte[] buffer = new byte[8192];
    int bytesRead;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {while ((bytesRead = inputStream.read(buffer)) != -1)
    {
        baos.write(buffer, 0, bytesRead);
    }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    bytes = baos.toByteArray();

    encodedFile = Base64.encodeToString(bytes, Base64.DEFAULT);
    return encodedFile;
}

推荐答案

尝试一下,

在Java中:

String encode = Base64.encodeToString(bytes, Base64.DEFAULT);

在php中:

$file = $_POST['file']['name'];

//$fname = $_POST['fname']['tmp_name'];

$fname = $_POST['file']['tmp_name'];

$file_path = "uploads/";
$actualpath = "http://harpal-projects.16mb.com/sbbs/$file_path/$file";

$sql = "INSERT INTO files (file,fname) VALUES ('$actualpath','$fname') ";

if(mysqli_query($con,$sql))
{

    file_put_contents(base64_decode($file), $file_path);
    echo "success";
}
else{

    echo "fail";
}

这篇关于使用截击上传pdf,但在服务器文件夹中获取空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆