这是我的android客户端代码,它将文件从android库发送到php服务器:
package com.example.upload;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.net.URL;
import com.loopj.android.http.RequestParams;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_IMG = 1;
String imgPath, fileName;
RequestParams params = new RequestParams();
String urlServer = "http://url.com/abc.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
int serverResponseCode;
String serverResponseMessage;
FileInputStream fileInputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button load = (Button)findViewById(R.id.buttonLoadPicture);
load.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
});
}
// When Image is selected from Gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
Log.v("imgPath", imgPath);
uploadImage();
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong" + e, Toast.LENGTH_LONG)
.show();
Log.v("Error",e.toString());
}
}
private void uploadImage() {
// TODO Auto-generated method stub
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
try {
fileInputStream = new FileInputStream(new File(imgPath));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + imgPath +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
Log.v("Response Message",serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
Log.v("Error",ex.toString());
}
return serverResponseMessage;
}
@Override
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(), "Successful" + serverResponseCode, Toast.LENGTH_LONG).show();;
}
}.execute(null,null,null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是我的PHP代码:
<?php
$target_path = "uploadedimages/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
}
else
{
echo "There was an error uploading the file, please try again!";
}
?>
我正在尝试将图像从我的Android客户端上传到php服务器。服务器响应消息给了我好的。服务器状态代码也给出200.因此,正在构建有效的http连接。但是,图像文件仍未上传到我的域中。 Logcat也不记录任何错误。我很困惑我哪里出错了。任何帮助将不胜感激。
答案 0 :(得分:0)
关于w3schools,这是我的解决方案: 将此代码用作php服务器端:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
$check = getimagesize($_FILES["file"]["tmp_name"]);
if ($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
if (file_exists($target_file)) {
$uploadOk = 0;
}
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
"jpeg"
&& $imageFileType != "gif"
) {
$uploadOk = 0;
}
if ($uploadOk == 0) {
$this->response(['status' => "failed"]);
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo json_encode(['status' => "success", "filename" =>
basename($_FILES["file"]["name"])]);
} else {
$this->response(['status' => "failed"]);
}
}
?>
并在jcenter()下的存储库部分的build.gradle文件中添加mavenCentral(),如下所示:
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
并在app gradle中添加以下行:
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'com.squareup.picasso:picasso:2.5.2'
并将这些权限添加到清单文件:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
并将以下代码添加为activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="ir.technopedia.myapplication.MainActivity">
<Button
android:id="@+id/btn_upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="Upload" />
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
</LinearLayout>
并将此代码添加为MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button btn;
ImageView img;
final int KeyGallery = 100, ReadExternalRequestCode = 200;
String url = "http://192.168.1.104/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_upload);
img = (ImageView) findViewById(R.id.img);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean result = checkPermission(MainActivity.this);
if (result)
galleryIntent();
}
});
}
public void uploadImage(File file) {
AsyncHttpClient myClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
try {
params.put("file", file);
} catch (FileNotFoundException e) {
}
myClient.post(url + "android/upload.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
JSONObject jsonObject = new JSONObject(new String(responseBody));
if (jsonObject.getString("status").equals("success")) {
Picasso.with(getBaseContext())
.load(url + "android/uploads/" + jsonObject.getString("filename"))
.into(img);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getBaseContext(), new String(responseBody), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
} else {
Uri selectedImage = data.getData();
if (selectedImage != null) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (!filePathColumn.equals(null)) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
if (!picturePath.equals(null)) {
uploadImage(new File(picturePath));
}
}
}
}
}
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), KeyGallery);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case ReadExternalRequestCode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
galleryIntent();
} else {
Toast.makeText(getBaseContext(), "permission problem!", Toast.LENGTH_LONG).show();
}
break;
}
}
public boolean checkPermission(final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ReadExternalRequestCode);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ReadExternalRequestCode);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
}
这肯定有用!享受...