我开发了一个应用程序从Android上传图像XAMPP服务器上的PHP文件.在Android的应用程序运行完美,图像显示为上传,没有出现错误,但当我进入服务器什么都没有.这里是我的Android代码和我的PHP代码:
安卓清单.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.androiddownloadmanagerdemo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
tools:targetApi="m">
<activity android:name=".AdvanceFileUpload"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
构建.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.androiddownloadmanagerdemo"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard- android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.squareup.okhttp3:okhttp:3.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso- core:3.2.0'
}
主要活动.java
package com.example.androiddownloadmanagerdemo;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
private static final int REQUEST_GALLERY = 200;
TextView file_name;
String file_path=null;
Button upload;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button upload_file=findViewById(R.id.upload_file);
upload_file.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//check permission greater than equal to marshmeellow we used run time permission
if(Build.VERSION.SDK_INT>=23){
if(checkPermission()){
filePicker();
}
else{
requestPermission();
}
}
else{
filePicker();
}
}
});
progressBar=findViewById(R.id.progress);
upload=findViewById(R.id.upload);
file_name=findViewById(R.id.filename);
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(file_path!=null){
UploadFile();
}
else{
Toast.makeText(MainActivity.this, "Please Select File First", Toast.LENGTH_SHORT).show();
}
}
});
Button advacneUpload=findViewById(R.id.advanceupload);
advacneUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,AdvanceFileUpload.class));
}
});
}
private void UploadFile() {
UploadTask uploadTask=new UploadTask();
uploadTask.execute(new String[]{file_path});
}
private void filePicker(){
//.Now Permission Working
Toast.makeText(MainActivity.this, "File Picker Call", Toast.LENGTH_SHORT).show();
//Let's Pick File
Intent opengallery=new Intent(Intent.ACTION_PICK);
opengallery.setType("image/*");
startActivityForResult(opengallery,REQUEST_GALLERY);
}
private void requestPermission(){
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(MainActivity.this, "Please Give Permission to Upload File", Toast.LENGTH_SHORT).show();
}
else{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE);
}
}
private boolean checkPermission(){
int result= ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result== PackageManager.PERMISSION_GRANTED){
return true;
}
else{
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSION_REQUEST_CODE:
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this, "Permission Successfull", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Permission Failed", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_GALLERY && resultCode== Activity.RESULT_OK){
String filePath=getRealPathFromUri(data.getData(),MainActivity.this);
Log.d("File Path : "," "+filePath);
//now we will upload the file
//lets import okhttp first
this.file_path=filePath;
File file=new File(filePath);
file_name.setText(file.getName());
}
}
public String getRealPathFromUri(Uri uri,Activity activity){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor=activity.getContentResolver().query(uri,proj,null,null,null);
if(cursor==null){
return uri.getPath();
}
else{
cursor.moveToFirst();
int id=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(id);
}
}
public class UploadTask extends AsyncTask<String,String,String>{
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
if(s.equalsIgnoreCase("true")){
Toast.makeText(MainActivity.this, "File uploaded", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Failed Upload", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... strings) {
if(uploadFile(strings[0])){
return "true";
}
else{
return "failed";
}
}
private boolean uploadFile(String path){
File file=new File(path);
try{
RequestBody requestBody=new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("files",file.getName(),RequestBody.create(MediaType.parse("image/*"),file))
.addFormDataPart("some_key","some_value")
.addFormDataPart("submit","submit")
.build();
Request request=new Request.Builder()
.url("https://"myIPv4adress"/projects/upload.php/")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
return true;
}
catch (Exception e){
e.printStackTrace();
return false;
}
}
}
}
上传.php
<?php
$target="uploads/".basename($_FILES['files']['name']);
if(isset($_POST['submit'])){
if(move_uploaded_file($_FILES['files']['tmp_name'],$target)){
echo "uploaded";
}
else{
echo "failed";
}
}
?>
2条答案
按热度按时间omjgkv6w1#
如果可以使用postman将图像上传到php服务器,则可以从postmanGenerating client code获取客户端代码
r1zk6ea12#
如果你想这样做,首先将图像转换为base64字符串,然后在后端将其转换为图像。
也许会有帮助