我正在创建一个Android移动应用程序,用户可以在其中将文件上传到服务器。
我使用以下代码成功将图像上传到服务器:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
我尝试使用以下代码发送文件,但它无法正常工作。
public String convertFileToBase64String(File f) throws IOException {
InputStream inputStream = new FileInputStream(f.getAbsolutePath());
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
bytes = baos.toByteArray();
String encodedFile = Base64.encodeToString(bytes, Base64.DEFAULT);
return encodedFile;
}
这里是上传的方法:
private void uploadFile(){
//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(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Dismissing the progress dialog
loading.dismiss();
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AppTheme);
builder.setMessage("Check your connection");
builder.setPositiveButton("OK", null);
builder.setCancelable(false);
builder.show();
} else if (error instanceof AuthFailureError) {
//TODO
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AppTheme);
builder.setMessage("Authentication Failure");
builder.setPositiveButton("OK", null);
builder.setCancelable(false);
builder.show();
} else if (error instanceof ServerError) {
//TODO
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AppTheme);
builder.setMessage("Error in server");
builder.setPositiveButton("OK", null);
builder.setCancelable(false);
builder.show();
} else if (error instanceof NetworkError) {
//TODO
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AppTheme);
builder.setMessage("An error in the network");
builder.setPositiveButton("OK", null);
builder.setCancelable(false);
builder.show();
} else if (error instanceof ParseError) {
//TODO
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AppTheme);
builder.setMessage("The server response could not be parsed");
builder.setPositiveButton("OK", null);
builder.setCancelable(false);
builder.show();
}
else
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String uploaded_file = null;
try {
uploaded_file = convertFileToBase64String(file);
} catch (IOException e) {
e.printStackTrace();
}
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_FILE, uploaded_file);
params.put(KEY_NAME, name);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
打开文件的方法:
public void openFile(String minmeType) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(minmeType);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", minmeType);
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null){
// it is device with samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Choose File");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
}
else {
chooserIntent = Intent.createChooser(intent, "Choose File");
}
try {
startActivityForResult(chooserIntent, FILE_REQUEST);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No suitable file manager has been found", Toast.LENGTH_SHORT).show();
}
}
OnActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
String FileName = data.getData().getLastPathSegment();
editTextName.setText(FileName);
}
}