我卡在那个地方,无法将doc文件发送到php服务器。 我正在使用此代码。
这是PHP代码。
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$name = $_POST['name'];
require_once('dbConnect.php');
$sql ="SELECT id FROM volleyupload ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.doc";
$actualpath = "http://10.0.2.2/VolleyUpload/$path";
$sql = "INSERT INTO volleyupload (photo,name) VALUES ('$actualpath','$name')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
这是Java代码
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("file/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE_REQUEST);
}
我在上传按钮上调用了asynTask。
if (v == buttonUpload) {
// uploadImage();
new PostDataAsyncTask().execute();
}
doInBackground中的函数调用是
private void postFile() {
try {
// the file to be posted
String textFile = Environment.getExternalStorageDirectory()
+ "/Woodenstreet Doc.doc";
Log.v(TAG, "textFile: " + textFile);
// the URL where the file will be posted
String postReceiverUrl = "http://10.0.2.2/VolleyUpload/upload.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
File file = new File(filePath.toString());
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
// you can add an if statement here and do other actions based
// on the response
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
我得到的例外是
java.io.FileNotFoundException: content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc: open failed: ENOENT (No such file or directory)
模拟器中有文件 - test.doc。 在代码中是否有任何我想念的东西,请帮助我。 或者建议将pdf上传到php服务器的教程。
提前致谢。
答案 0 :(得分:8)
以下是我的问题的解决方案: - 这是php文件的代码 - file.php
<?php
// DISPLAY FILE INFORMATION JUST TO CHECK IF FILE OR IMAGE EXIST
echo '<pre>';
print_r($_FILES);
echo '</pre>';
// DISPLAY POST DATA JUST TO CHECK IF THE STRING DATA EXIST
echo '<pre>';
print_r($_POST);
echo '</pre>';
$file_path = "images/";
$file_path = $file_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
echo "file saved success";
} else{
echo "failed to save file";
}?>
将此文件放在测试命名文件夹内的Xampp的htdoc文件夹中(如果已经有测试文件夹,那么确定,否则创建一个名为&#34的文件夹;测试&#34;)。并创建一个名为&#34; images&#34;的文件夹,其中保存了上传的文件。
创建从库中选择文件的功能
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
1);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
在onActivityResult函数内部
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedFileURI = data.getData();
File file = new File(selectedFileURI.getPath().toString());
Log.d("", "File : " + file.getName());
uploadedFileName = file.getName().toString();
tokens = new StringTokenizer(uploadedFileName, ":");
first = tokens.nextToken();
file_1 = tokens.nextToken().trim();
txt_file_name_1.setText(file_1);
}
}
这是将文件上传到服务器的asyncTask,
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please wait ...");
showDialog();
}
@Override
protected String doInBackground(String... strings) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://10.0.2.2/test/file.php");
file1 = new File(Environment.getExternalStorageDirectory(),
file_1);
fileBody1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file1", fileBody1);
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
final String responseStr = EntityUtils.toString(resEntity)
.trim();
Log.v(TAG, "Response: " + responseStr);
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
hideDialog();
Log.e("", "RESULT : " + result);
}
}
从图库中选择文件后,按下按钮调用asyncTask。
btn_upload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new PostDataAsyncTask().execute();
}
});
希望这会对你有所帮助。 乐意帮助和快乐编码。
答案 1 :(得分:0)
下面的代码没有经过测试(按原样),但通常是如何处理文件上传的 - 正如您将看到的,那里有一个调试语句。尝试发送文件,看看你得到了什么〜如果所有人都好,请注释掉那条线并保持手指交叉。
<?php
/* Basic file upload handler - untested */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES['image'] ) && !empty( $_FILES['image']['tmp_name'] ) ){
/* Assuming the field being POSTed is called `image`*/
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
$tmp = $_FILES['image']['tmp_name'];
/* debug:comment out if this looks ok */
exit( print_r( $_FILES,true ) );
$result = $status = false;
$basename=pathinfo( $name, PATHINFO_FILENAME );
$filepath='http://10.0.2.2/VolleyUpload/'.$basename;
$result=@move_uploaded_file( $tmp, $filepath );
if( $result ){
$sql = "insert into `volleyupload` ( `photo`, `name` ) values ( '$filepath', '$basename' )";
$status=mysqli_query( $con, $sql );
}
echo $result && $status ? 'File uploaded and logged to db' : 'Something not quite right. Uploaded:'.$result.' Logged:'.$status;
}
?>
答案 2 :(得分:0)
java.io.FileNotFoundException:
content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc:
open failed: ENOENT (No such file or directory)
您拥有的是内容提供商路径。不是文件系统路径。 所以你不能使用File ...类。
改为使用
InputStream is = getContentResolver().openInputStream(uri);
其余的PHP代码没有意义,因为上传时没有base64编码。此外,$ path和$ actualpath参数未被使用和混淆。你没有说出你的剧本应该做什么。