Android H5拍照或選擇上傳圖片+WebApi服務端儲存檔案
阿新 • • 發佈:2018-12-26
H5拍照+H5選照片
<em id="clock_imgs"></em><a href="javascript:captureImage();">選擇圖片</a>
<button type="button" id="submit" >提交</button>
var files = [],index = 1; // 拍照 function captureImage() { if(files.length >= 5) { alert('最多隻能上傳5張照片'); return; } var actionbuttons = [{ title: "拍照" }, { title: "從相簿中選擇" }]; var actionstyle = { title: "選擇圖片", cancel: "取消", buttons: actionbuttons }; plus.nativeUI.actionSheet(actionstyle, function(e) { switch(e.index) { case 1: //拍照 plus.camera.getCamera().captureImage(function(p) { appendFile(p); }); break; case 2: //從相簿中選擇 plus.gallery.pick(function(p) { appendFile(p); }); break; } }); } // 顯示 function appendFile(p) { plus.io.resolveLocalFileSystemURL(p, function(entry) { console.log(p); console.log(entry.toLocalURL()); var path = entry.toLocalURL(); $("#clock_imgs").append('<img src '+path+'/>'); files.push({ name: "uper" + index, path: path }); index++; $('#clock_imgs>img').click(function() { $(this).remove(); files.splice($(this).index(), 1); }); }, function(e) { alert('讀取照片檔案錯誤:' + e.message); }); }
H5上傳檔案
$("#submit").click(function() { if(files.length <= 0) { alert('請拍照或選擇照片'); return; } plus.nativeUI.showWaiting();//顯示載入圖示 var task = plus.uploader.createUpload(//建立上傳任務 'http://api.chinalzw-cloud.com/api/uploader'//上傳伺服器連線 , {method: "POST"},//post請求 function(t, status) {//返回結果 plus.nativeUI.closeWaiting();//隱藏載入圖示 console.log(JSON.stringify(t)); console.log(status); //上傳成功 if(status == 200) { alert("上傳成功:" + status); alert('打卡成功:當前時間' + new Date().toString()); } else { alert("上傳失敗:" + status); } } ); task.addData("uid", "value");//設定POST引數uid,根據需求傳post引數 for(var i = 0; i < files.length; i++) {//for迴圈新增需要上傳的檔案 var f = files[i]; task.addFile(f.path, { key: f.name }); } task.start(); });
WebApi服務端
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using System.IO; namespace API.Controllers { public class UploaderController : ApiController { /// <summary> /// 上傳檔案 /// </summary> /// <returns></returns> [Route("~/uploader"), HttpPost] public string Post() { if (HttpContext.Current.Request.Form["uid"] == null) { return "缺少uid引數。"; } //POST引數 int uid = Convert.ToInt32(HttpContext.Current.Request.Form["uid"]); string r = ""; try { HttpFileCollection files = HttpContext.Current.Request.Files; if (files != null && files.Count > 0) { for (int i = 0; i < files.Count; i++) { HttpPostedFile file = files[i]; string filePath = HttpContext.Current.Server.MapPath("~/upload_files/") + file.FileName; file.SaveAs(filePath); } } return "上傳成功。userid:"+ userid; } catch (Exception ex) { return "上傳失敗。"; } } } }