Android 图片上传

Posted linkai1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 图片上传相关的知识,希望对你有一定的参考价值。

上传方式:两种
 
1:Base64()
(1):获取图片路径,将图片转为String 类型
(2):通过post提交的方式.以键值对的方式上传到服务器,和一般的提交关键字没有任何区别.
(3):这种适用于图片少的时候使用.
 
转码代码如下:
 
public class Base64Code {
 
// constructor
public Base64Code() {
 
}
 
/**
* Encode image to Base64 string
* @param srcPath
* @return Base64 encoded string
*/
public static String encodeImageToBase64String(String srcPath) {
 
Log.d("srcPath:", srcPath);
 
String imageString = null;
InputStream inputStream;
try {
inputStream = new FileInputStream(srcPath);
//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
inputStream.close();
 
bytes = output.toByteArray();
imageString = Base64.encodeToString(bytes, 0, bytes.length, Base64.NO_WRAP);
 
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
 
return imageString;
}
}
 
2:以IO流的形式进行提交(表单提交)
 
代码如下:
 
 
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
 
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(fileUrl);
 
if (!sourceFile.isFile()) {
dialog.dismiss();
 
runOnUiThread(new Runnable() {
 
public void run() {
messageText.setText("Source File not exist :" + fileUrl);
}
});
 
return 0;
}
 
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(uploadUrl);
 
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don‘t use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
 
dos = new DataOutputStream(conn.getOutputStream());
 
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
 
dos.writeBytes(lineEnd);
 
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
 
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
 
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
 
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
 
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
 
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
 
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
 
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
 
public void run() {
Toast.makeText(UploadToServerActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
 
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
 
 
使用第三方框架Xutils 进行图片上传步骤(也称为表单提交)
 
第一步:首先还是在application中初始化:
  1. x.Ext.init(this);
第二步:然后使用org.xutils.http包下的RequestParams来构造参数
params = new RequestParams(url);
//上传图片的关键方法.键值对
params.addBodyParameter("upload", new File(fileName));
第三步:使用Callback.Cancekable来进行请求回调:
Callback.Cancelable cancelable
  1. = x.http().post(params, new Callback.CommonCallback<ResponseEntity>() {

  2. @Override
  3. public void onSuccess(ResponseEntity result) {
  4. Snackbar.make(view, "上传成功", Snackbar.LENGTH_LONG)
  5. .setAction("Action", null).show();
  6. }

  7. @Override
  8. public void onError(Throwable ex, boolean isOnCallback) {

  9. Snackbar.make(view, "上传失败", Snackbar.LENGTH_LONG)
  10. .setAction("Action", null).show();

  11. }

  12. });
以上三步就可以完成图片上传.





以上是关于Android 图片上传的主要内容,如果未能解决你的问题,请参考以下文章

android批量文件上传(android批量图片上传)

Android仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等

Android使用Retrofit技术仿微信图片上传,可以选择多张图片拍照上传

Android 图片上传

Android高仿微信图片选择上传工具

android 批量上传图片