网上有很多关于拍照上传的实现方法,如果用新版本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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。