【Android 图片上传】少年恃险若平地,独倚长剑凌清秋。这篇文章主要讲述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中初始化:
- x.Ext.init(this);
- = x.http().post(params, new Callback.CommonCallback< ResponseEntity> () {
-
- @Override
- public void onSuccess(ResponseEntity result) {
- Snackbar.make(view, "上传成功", Snackbar.LENGTH_LONG)
- .setAction("Action", null).show();
- }
- @Override
- public void onError(Throwable ex, boolean isOnCallback) {
- Snackbar.make(view, "上传失败", Snackbar.LENGTH_LONG)
- .setAction("Action", null).show();
- }
- });
推荐阅读
- Android 中算法问题
- android 观察者模式
- Android图片下载到本地,系统图库不显示
- Android_JNI
- Android为啥推荐用DialogFragment创建Dialog?
- 跟着Innost理解下Android控件(ViewRoot)系统
- 我的Android进阶之旅如何在浏览器上使用Octotree插件树形地展示Github项目代码()
- Android之线程池深度剖析
- Android开发5(应用程序窗口小部件App Widgets的实现)