我知道我的问题已经有很多问题和教程了。但我没有得到任何教程来上传除图像以外的文件。
我按照一个示例设法将图像成功上传到localhost。但是,我想上传pdf,docx,pptx等文件。不仅限于图像。
我遵循了本教程:http://programmerguru.com/android-tutorial/how-to-upload-image-to-php-server/
我是android的初学者,所以我不知道在更改原始代码时我在做什么。到目前为止,我的MainActivity.java已经给出,结果是出了问题'单击上传按钮时崩溃。
public class MainActivity extends Activity {
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String filePath, fileName;
Bitmap bitmap;
private static int RESULT_LOAD_FILE = 1;
TextView viewFileName;@
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prgDialog = new ProgressDialog(this);
// Set Cancelable as False
prgDialog.setCancelable(false);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// Start the Intent
startActivityForResult(intent, RESULT_LOAD_FILE);
}
// When Image is selected from Gallery
@
Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
viewFileName.setText("File Name: \n" + data.getData().getLastPathSegment() +
"\n");
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_FILE && resultCode == RESULT_OK &&
null != data) {
// Get the Image from data
Uri selectedFile = data.getData();
String[] filePathColumn = {
MediaStore.Files.FileColumns.DATA
};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedFile,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView
imgView.setImageBitmap(BitmapFactory.decodeFile(filePath));
// Get the Image's file name
String fileNameSegments[] = filePath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
// Put file name in Async Http Post Param which will used in Php web app
params.put("filename", fileName);
} else {
Toast.makeText(this, "You haven't picked any file", Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
// When Upload button is clicked
public void uploadImage(View v) {
// When Image is selected from Gallery
if (filePath != null && !filePath.equals("")) {
prgDialog.setMessage("Converting Image to Binary Data");
prgDialog.show();
// Convert image to String using Base64
encodeImagetoString();
// When Image is not selected from Gallery
} else {
Toast.makeText(getApplicationContext(),
"You must select image from gallery before you try to upload",
Toast.LENGTH_LONG).show();
}
}
// AsyncTask - To convert Image to String
public void encodeImagetoString() {
new AsyncTask < Void, Void, String > () {
protected void onPreExecute() {};@
Override
protected String doInBackground(Void...params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(filePath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 50,
stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}@
Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("Calling Upload");
// Put converted Image string into Async Http Post param
params.put("image", encodedString);
// Trigger Image upload
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
makeHTTPCall();
}
// Make Http call to upload Image to Php server
public void makeHTTPCall() {
prgDialog.setMessage("Invoking Php");
AsyncHttpClient client = new AsyncHttpClient();
// Don't forget to change the IP address to your LAN address. Port no as well.
client.post("http://10.16.36.144:8080/imgupload/upload_image.php",
params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
@
Override
public void onSuccess(String response) {
// Hide Progress Dialog
prgDialog.hide();
Toast.makeText(getApplicationContext(),
response, Toast.LENGTH_LONG).show();
}
// When the response returned by REST has Http
// response code other than '200' such as '404',
// '500' or '403' etc
@
Override
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(),
"Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : " +
statusCode, Toast.LENGTH_LONG).show();
}
}
});
}@
Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Dismiss the progress bar when application is closed
if (prgDialog != null) {
prgDialog.dismiss();
}
}
}
编辑 应用程序崩溃后的logcat
FATAL EXCEPTION: main
Process: com.example.habibah.uploadtoserverv4, PID: 3840
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/1504-0F18:8MSFDPo.jpg flg=0x1 }} to activity {com.example.habibah.uploadtoserverv4/com.example.habibah.uploadtoserverv4.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3577)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3620)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.habibah.uploadtoserverv4.MainActivity.onActivityResult(MainActivity.java:56)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3573)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3620)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)