网上有很多关于拍照上传的实现方法,如果用新版本android去运行有可能会发现根本实现不了。主要原因是android从4.4版本开始通过intent.ACTION_GET_CONTENT打开选择器后,getData()返回的URI没有包含真实的文件路径,而是像这样“content://com.android.providers.media.documents/document/image:1234”,以至于用传统的方式找不到图片的路径。最简单的解决办法是用intent.ACTION_PICK代替intent.ACTION_GET_CONTENT。
下面给出4.4版本后拍照上传的具体实现方法:
第一步:点击拍照按钮代码
//点击拍照
btnHeadCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent itCamera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(itCamera,0);
}
});
第二步:保存拍照图片代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case 0://拍照
savePhoto(data);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
final String SAVE_PATH=Environment.getExternalStorageDirectory()+"/my_head.jpg"; //拍照后保存路径 //保存图片 public void savePhoto(Intent it){
Bundle bundle=it.getExtras();
if(bundle!=null){
Bitmap photo = bundle.getParcelable("data");
imgHead.setImageBitmap(photo);
File fileHead=new File(SAVE_PATH);
try {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
if(!fileHead.getParentFile().exists()){
fileHead.getParentFile().mkdir();
}
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(fileHead));
photo.compress(Bitmap.CompressFormat.JPEG,80,bos);
bos.flush();
bos.close();
}else {
Toast toast = Toast.makeText(HeadPhotoActivity.this, "保存失败!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
第三步:上传图片代码
String SERVER_URL = Config.PhotoAPI+"/UploadImage";//上传的服务端API地址btnHeadCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(SAVE_PATH);
Message msg = new Message();
msg.what = 0;
if(file!=null) {
try {
int re = ImageUtils.uploadForm(file, SERVER_URL);
msg.obj = re;
} catch (IOException ex) {
msg.obj = 0;
Toast.makeText(HeadPhotoActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
}
handler.sendMessage(msg);
}else {
Toast.makeText(HeadPhotoActivity.this, "找不到上传图片", Toast.LENGTH_SHORT).show();
}
}
}).start();
}
});
final Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
if ((int)msg.obj == 1) {
Toast.makeText(HeadPhotoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HeadPhotoActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public static int uploadForm(File uploadFile, String serverUrl)
throws IOException {
int re=0;
String fileName = uploadFile.getName();
StringBuilder sb = new StringBuilder();
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"" + fileName
+ "\"; filename=\"" + fileName + "\"" + "\r\n");
sb.append("Content-Type: image/jpeg" + "\r\n");
sb.append("\r\n");
byte[] headerInfo = sb.toString().getBytes("UTF-8");
byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
System.out.println(sb.toString());
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Content-Length", String
.valueOf(headerInfo.length + uploadFile.length()
+ endInfo.length));
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
InputStream in = new FileInputStream(uploadFile);
out.write(headerInfo);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1)
out.write(buf, 0, len);
out.write(endInfo);
in.close();
out.close();
if (conn.getResponseCode() == 200) {
re=1;
}
return re;
}
最后给出服务端WebAPI代码:
[HttpPost]
public async Task<HttpResponseMessage> UploadImage()
{string filePath = "~\\UploadFiles\\Photo";
// 取得文件夹
string dir = HttpContext.Current.Server.MapPath(filePath);
//如果不存在文件夹,就创建文件夹
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new CustomMultipartFormDataStreamProvider(dir);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
//file.Headers.ContentDisposition.FileName;//上传文件前的文件名
//file.LocalFileName;//上传后的文件名
Photo p = new Photo();
p.ImgInfo = file.LocalFileName.Substring(file.LocalFileName.LastIndexOf("\\"));
p.Sort = "员工相册";
p.AddUser = "admin";
p.AddTime = DateTime.Now;
p.Url = filePath + p.ImgInfo;
db.Photo.Add(p);
db.SaveChanges();
}
return Request.CreateResponse(HttpStatusCode.OK); }
catch
{
return Request.CreateResponse(HttpStatusCode.BadRequest); }
}
//重写上传文件名
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path)
: base(path)
{ }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
return fileName + "_" + headers.ContentDisposition.FileName.Replace("\"", string.Empty);//base.GetLocalFileName(headers);
}
}
您可能感兴趣的文章:android 微信 sdk api调用不成功解决方案android monkey自动化测试改为java调用monkeyrunner ApiAndroid 高版本API方法在低版本系统上的兼容性处理Android 调用百度地图API示例android开发教程之获取使用当前api的应用程序名称android通过google api获取天气信息示例android通过Location API显示地址信息的实现方法Android通过原生APi获取所在位置的经纬度Android提高之蓝牙隐藏API探秘Android指纹识别API初试Android开发学习笔记之通过API接口将LaTex数学函数表达式转化为图片形式Android 支付宝支付、微信支付、银联支付 整合第三方支付接入方法(后台订单支付API设计)使用android隐藏api实现亮度调节的方法Android API开发之SMS短信服务处理和获取联系人的方法Android 用 camera2 API 自定义相机Android基于API的Tabs3实现仿优酷tabhost效果实例Android 多媒体播放API简单实例最新Android版本、代号、对应API/NDK级别、发布时间及市场份额