Android4.4 WebAPI实现拍照上传功能
程序员文章站
2024-03-05 12:54:54
网上有很多关于拍照上传的实现方法,如果用新版本android去运行有可能会发现根本实现不了。主要原因是android从4.4版本开始通过intent.action_get_...
网上有很多关于拍照上传的实现方法,如果用新版本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; } } };
/** * * @param uploadfile * 需要上传的文件 * @param serverurl * 上传的服务器的路径 * @throws ioexception */ 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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。