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);
第二步:然后使用org.xutils.http包下的RequestParams来构造参数
params = new RequestParams(url);
//上传图片的关键方法.键值对
params.addBodyParameter("upload", new File(fileName));
第三步:使用Callback.Cancekable来进行请求回调:
Callback.Cancelable cancelable
- = 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();
- }
- });
以上三步就可以完成图片上传.