【发布时间】:2016-04-27 06:25:02
【问题描述】:
我正在使用托管域数据库中的 volley 库以及同一托管域的文件夹中上传 pdf 文件
这是我的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 的服务器文件夹中
这是我的 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,即它为空,所以它没有用...告诉我如何修改此代码.??
我尝试了 convertFileToBase64String,但它也得到了空文件
在 activtyonresult 我试过这个代码
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);
当我使用 toast 来查看 encodedBase64 的长度时,结果为 0 ,对于 'file','fileinputreader','bytes' 相同
所以我认为这是不对的,或者可能是我错了..纠正我
我尝试了这段代码,但它得到了空值......好像我没有选择任何文件或者文件在某个地方丢失了......
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;
}
【问题讨论】:
-
你的 php 代码很糟糕。您应该做的第一件事是检查您的数据是否进入。从 isset($_POST['file']) 开始。如果未设置,请不要继续,但会回显适当的消息。
-
“fname”是否正确接收?你应该告诉我们更多。
-
String getStringFile(File f)。您不能将图像文件或 pdf 文件放在字符串中。 -
base64_decode($file)。您没有发送 base64 编码的 pdf 文件。 -
从 String getStringFile(File f) 开始,我无法将文件放入字符串中...但这里我将文件转换为 InputStream,然后将 BufferedReader 与该输入流一起使用,我将文件转换为字符串上传到服务器。 @greenApps 'public String getStringFile(File f) { StringBuilder sb = new StringBuilder();尝试 { FileInputStream fileInputStream = new FileInputStream(f); BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));'
标签: android mysql xml android-studio