将 pdf 文件上传到服务器并获取其 url

Upload pdf file to server and get its url

我希望用户将 pdf 上传到服务器并使其可下载到其他 user.I 想将上传文件的 url 保存到数据库,然后选择 url 以显示其他用户。我正在学习 android ,所以我没有太多想法。 这是我的代码,我曾尝试使用 multipart:-

public class Upload extends Activity {
String path=null;
private String getpath(String path){
    return path;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
Button browse = (Button) findViewById(R.id.browse);
Button upload = (Button) findViewById(R.id.upload);
browse.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        Intent intent = new Intent();
        intent.setType("application/pdf");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select PDF"), 1);


    }

});

upload.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        upload up = new upload(); 
        up.execute();

    }
});

}
 public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
    if (requestCode == 1) {
        Uri data = result.getData();
         String pathe = data.getPath();
         path = getpath(pathe);
         Toast.makeText(Upload.this, path, Toast.LENGTH_SHORT).show();
}
}
}




private class upload extends AsyncTask<Void, Void, Void>{
ProgressDialog pd;
@Override
protected void onPreExecute() {
pd= ProgressDialog.show(Upload.this, "Uploading", "Please Wait");
super.onPreExecute();
}
@Override
    protected void onPostExecute(Void result) {
    pd.dismiss();
    super.onPostExecute(result);
    }
@Override
protected Void doInBackground(Void... params) {
    //Toast.makeText(Upload.this, path,Toast.LENGTH_LONG).show();

    String url = "http://192.168.43.50/projectpri/upload.php";
    File file = new File(path);
    file.getAbsolutePath();
    try {
        HttpClient httpclient = new DefaultHttpClient();   
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(url);
        MultipartEntity mpe = new MultipartEntity();
        ContentBody cbfile =new FileBody(file);
        mpe.addPart("file", cbfile);
        httppost.setEntity(mpe);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity ent = response.getEntity();
        System.out.println(response.getStatusLine());

    } catch (Exception e) {
        // show error
    }
    return null;
}

}

完整的工作示例,针对超过 100 Mb 的文件进行了测试,将 your_package 替换为您的包名称。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your_package" >

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

布局activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Browse"
        android:id="@+id/browse"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload"
        android:id="@+id/upload"/>
</LinearLayout>

Activity 主要Activity

package your_package;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    Uri path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button browse = (Button) findViewById(R.id.browse);
        Button upload = (Button) findViewById(R.id.upload);

        browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setType("application/pdf");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select PDF"), 1);
            }
        });
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                (new Upload(MainActivity.this, path)).execute();

            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                path = result.getData();
            }
        }
    }
}

class Upload extends AsyncTask<Void, Void, Void> {
    private ProgressDialog pd;
    private Context c;
    private Uri path;

    public Upload(Context c, Uri path) {
        this.c = c;
        this.path = path;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = ProgressDialog.show(c, "Uploading", "Please Wait");
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        pd.dismiss();
    }

    @Override
    protected Void doInBackground(Void... params) {
        String url_path = "http://192.168.43.50/projectpri/upload.php";
        HttpURLConnection conn = null;

        int maxBufferSize = 1024;
        try {
            URL url = new URL(url_path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setChunkedStreamingMode(1024);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data");

            OutputStream outputStream = conn.getOutputStream();
            InputStream inputStream = c.getContentResolver().openInputStream(path);

            int bytesAvailable = inputStream.available();
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[] buffer = new byte[bufferSize];

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            inputStream.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                Log.i("result", line);
            }
            reader.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }
}

服务器端PHP

$file_name = date("U").".pdf"; //name of your file
$server_path = "/path/to/file/folder/"; //server path to folder
$web_path = "http://192.168.43.50/projectpri/file/"; //web path to folder

$file = $server_path.$file_name;
file_put_contents($file,"");

$fp = fopen("php://input", 'r');
while ($buffer =  fread($fp, 8192)) {
    file_put_contents($file,$buffer,FILE_APPEND | LOCK_EX);
}

echo $web_path.$file_name;

首先,您不应该使用 HttpClient、MultipartEntitiy,因为它们 已弃用 并且根本不使用并且 不推荐 http://developer.android.com/.

  • 我也用过你的这些类,但是是时候升级到市场,用现在的androidM更新了。
  • 我也知道 Internet 上的大多数教程都与 HttpClient 等相关,这些对当前时间没有用去寻找 HttpUrlConnection.

为方便起见,请查看以下链接:

常识:

http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html

post 为您提供有用的服务器链接:

http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

For posting data to server you can also use library with less effort like volley, Retrofit. etc.

您必须对其进行一些实验,这将确保您的代码未来围绕各种 android 版本有效地运行。

谢谢