Android 图片上传
来源:互联网 发布:修改苹果手机型号软件 编辑:程序博客网 时间:2024/05/21 17:52
上传方式:两种
1:Base64()
(1):获取图片路径,将图片转为String 类型
(2):通过post提交的方式.以键值对的方式上传到服务器,和一般的提交关键字没有任何区别.
(3):这种适用于图片少的时候使用.
转码代码如下:
publicclassBase64Code {
// constructor
publicBase64Code() {
}
/**
* Encode image to Base64 string
* @param srcPath
* @return Base64 encoded string
*/
publicstaticString encodeImageToBase64String(String srcPath) {
Log.d("srcPath:", srcPath);
String imageString =null;
InputStream inputStream;
try{
inputStream =newFileInputStream(srcPath);
//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = newbyte[8192];
intbytesRead;
ByteArrayOutputStream output =newByteArrayOutputStream();
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();
}
returnimageString;
}
}
2:以IO流的形式进行提交(表单提交)
代码如下:
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
HttpURLConnection conn =null;
DataOutputStream dos =null;
String lineEnd ="\r\n";
String twoHyphens ="--";
String boundary ="*****";
intbytesRead, bytesAvailable, bufferSize;
byte[] buffer;
intmaxBufferSize =1* 1024* 1024;
File sourceFile =newFile(fileUrl);
if(!sourceFile.isFile()) {
dialog.dismiss();
runOnUiThread(newRunnable() {
publicvoidrun() {
messageText.setText("Source File not exist :"+ fileUrl);
}
});
return0;
}
FileInputStream fileInputStream =newFileInputStream(sourceFile);
URL url =newURL(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 =newDataOutputStream(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 =newbyte[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(newRunnable() {
publicvoidrun() {
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.Cancelablecancelable
- = 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();
- }
- });
以上三步就可以完成图片上传.
0 0
- Android 选择图片、上传图片
- Android URL上传图片
- android HttpClient 上传图片
- android HttpClient 上传图片
- android图片上传
- android图片上传服务器
- android上传图片
- android 上传图片
- android图片压缩上传
- Android 图片压缩上传
- Android 上传图片
- Android Base64上传图片
- Android 上传文件,图片
- android图片上传
- android图片上传
- android 上传图片
- Android 上传/下载图片
- Android图片上传
- 模拟器之王Genymotion下载安装及常见问题汇总
- unity socket编程过程
- c#数据结构--数组
- 利用U盘重装win系统
- Android更新升级的测试
- Android 图片上传
- QProgressBar(进度条)的使用
- window 8.1版本安装CUDA8.0
- 安装第三方库出现 Python version 2.7 required, which was not found in the registry
- 什么是Ad-hoc Query
- Android SDK上手指南:用户界面设计
- 递归剖析
- delphi fmx idhttp post 案列,android测试通过
- 网络游戏服务器之 日志系统