1. The server uses the. NET WEBAPI interface.
2.android multi-File upload.
The following is the core code:
1 package com.example.my.androidupload; 2 3 4 Import Android.util.Log; 5 6 Import Java.io.File; 7 Import java.io.Serializable; 8 Import Java.util.Iterator; 9 Import Java.util.LinkedHashMap; Ten import Java.util.Map; Import Java.util.Map.Entry; Import org.apache.http.Consts; Import org.apache.http.HttpEntity; Org.apache.http.HttpResponse import; Org.apache.http.client.HttpClient import; + Import Org.apache.http.client.methods.HttpPost; Import Org.apache.http.entity.ContentType; Import Org.apache.http.entity.mime.MultipartEntityBuilder; Import Org.apache.http.entity.mime.content.FileBody; Org.apache.http.entity.mime.content.StringBody import; Import org.apache.http.impl.client.DefaultHttpClient; Org.apache.http.util.EntityUtils import; /** * Created by wz on 2016/04/19. */Httpclientutil public final static String method_post = "POST"; String method_get = "GET"; 31 32 /** * Multipart/form-data Types of forms submitted by * * * * @param form data * */PNS public static String SUBM Itform (Multipartform form) {38//return string responsestr = ""; 40 41//Create HttpClient instance/* Httpclientbuilder Httpclientbuilder = httpclientbuilder.create (); Closeablehttpclient httpClient = Httpclientbuilder.build (); */Closeablehttpclient httpclient= HTT Pclients.createdefault (); HttpClient HttpClient = new Defaulthttpclient (); try {48//Instantiation submission Request HttpPost HttpPost = new HttpPost (Form.getaction ()); 50 51 Create Multipartentitybuilder Multipartentitybuilder Entitybuilder = Multipartentitybuilder.create (); LOG.E ("Httpclientutil", "111"); 55//Append normal form field map<string, string> normalfieldmap = Form.getnormalfield (); Iterator<entry<string, string>> itErator = Normalfieldmap.entryset (). iterator (); Iterator.hasnext (); ) {entry<string, string> entity = Iterator.next (); Entitybuilder.addpart (Enti Ty.getkey (), New Stringbody (Entity.getvalue (), Contenttype.create ("Text/plain", Consts.utf_8))); LOG.E ("Httpclientutil", "222"); 62//Append file field map<string, file> filefieldmap = Form.getfilefield (); A for (iterator<entry<string, file>> Iterator = Filefieldmap.entryset (). Iterator (); iterator.hasn Ext (); ) {entry<string, file> entity = Iterator.next (); Entitybuilder.addpart (Entity . GetKey (), New Filebody (Entity.getvalue ())); "LOG.E" ("Httpclientutil", "333"); 69//Set Request entity Httppost.setentity (Entitybuilder.build ()); LOG.E ("Httpclientutil", "444"); 72//Send request HttpResponse response= Httpclient.execute (HttpPost); StatusCode int = Response.getstatusline (). Getstatuscode (); 75//Get response data httpentity resentity = Response.getentity (); LOG.E ("Httpclientutil", "Result:" + integer.tostring (StatusCode)); if (statusCode) {resentity! = null) {RESPONSESTR = E Ntityutils.tostring (resentity); Bayi} (Exception e) {System.out.println} ("Submit form failed, Reason:" + E.getmessage ()); The finally {try {Httpclient.getconnectionmanager (). Shutdown (); 88 } catch (Exception ex) {RESPONSESTR} 92} 93 94/** 95 * form Field Bean */$ public Class Multipartform implements Serializable {98 /** 99 * Serial number */101 private static final long Serialversionuid = 2138044819190537198L;102 103/**104 * Submit URL105 **/106 private String action = ""; 107 108 /**109 * Submission Method: post/get110 **/111 Private String method = "POST"; 112 113/**114 * Normal form field **/116 private map<string, string> Normalfield = new linkedhashmap<string, String> ;(); 117 118/**119 * file fields **/121 private map<string, file> Filefield = new Link Edhashmap<string, file> (); 122 123 public String getaction () {124 return action;125}126 127 public void Setaction (String action) {$ this.action = action;129}130 131 public String GetMethod () {method;133 return}134 135 public void Setmethod (string method) {136 This.method = method;137}138 139 public map<string, string> Getnormalfield () {140 Return Normalfield;141}142 143 public void Setnormalfield (map<string, string> Normalfield) {144 This.nor Malfield = normalfield;145}146 147 public map<string, file> Getfilefield () {148 return filefield;149}150 151 public void Setfilefield (map<string, file> Filefield) {THIS.F Ilefield = filefield;153}154 155 public void Addfilefield (String key, File value) {156 Filefi Eld.put (key, value); 157}158 159 public void Addnormalfield (string key, String value) { Malfield.put (key, value); 161}162}163 164 165}
Call:
public class Mainactivity extends Appcompatactivity implements View.onclicklistener {private Button mbtnupload; @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_upload: {n EW Thread (New Runnable () {@Override public void run () {Http Clientutil httpClient = new Httpclientutil (); Httpclientutil.multipartform form = Httpclient.new multipartform (); Set the form property, parameter Form.setaction ("Http://192.168.1.5:9001/api/Mobile/FileUpload/UploadFile"); String path= environment.getexternalstoragedirectory (). GetPath () + "/DCIM" + "/20151120_051052.jpg"; LOG.E ("One", path); File File = new file (path); Form.addfilefield ("file", file); Form.addnormalfield ("ID", "301201604"); StringResultCode = Httpclient.submitform (form); LOG.E ("Upload result:", ResultCode); }}). Start (); Break }}} @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancest ATE); Setcontentview (R.layout.activity_main); Mbtnupload = (Button) Findviewbyid (r.id.btn_upload); Mbtnupload.setonclicklistener (this); }}
Server-side code (developed by. NET Webapi):
1//<summary> 2///Attachment upload 3//</summary> 4 [Routeprefix ("Api/mobile/fileupload")] 5 public class Fileuploadcontroller:apicontroller 6 {7 static readonly string uploadfolder = "/upload/ap Iupload "; 8 static readonly String serveruploadfolder = HttpContext.Current.Server.MapPath (Uploadfolder); 9 #region Upload file-file information is not saved to the database//<summary> 13//Upload file-file information not saved to database 14//& lt;/summary>//<returns> return file information </returns> [HttpPost] [Route ("UploadFile") ] public async task<list<fileresultdto>> UploadFile () {Log.info ("UPLOADF Ile "," enter "); 21 22//Verify that this is an HTML form file upload request. Request.Content.IsMimeMultipartContent ("Form-data")) {Log.info ("UploadFile", "Error01") ; -Throw new Httpresponseexception (Request.createresponse (HtTpstatuscode.unsupportedmediatype)); +//Create a stream provider for setting up output streams Multipart Formdatastreamprovider Streamprovider = new Renamingmultipartformdatastreamprovider (ServerUploadFolder); +//Read The MIME multipart asynchronously content using the stream provider we just created. Request.Content.ReadAsMultipartAsync await (Streamprovider); Log.info ("UploadFile", "enter 01"); list<fileresultdto> itemList = new list<fileresultdto> (); Multipartfiledata file in Streamprovider.filedata ("U-Log.info") Ploadfile "," enter 02 "); FileInfo FileInfo = new FileInfo (file. LocalFilename); FILERESULTDTO item = new Fileresultdto (); var slocalfilename = file. LocalFilename; String fileName = Slocalfilename.substring (slocalfilename. LastIndexOf ("\ \") + 1, slocalfilename.length-slocalfilename.lastindexof ("\ \")-1); Item.id = Guid.NewGuid (); Item. FileName = file. Headers.ContentDisposition.FileName; The item. Serverfilename = Fileinfo.name; The item. FileSize = Fileinfo.length; Item. FilePath = Uploadfolder; The item. Fullfilepath = Serveruploadfolder; The item. ContentType = file. Headers.ContentType.MediaType.ToString (); The item. Uploadtime = DateTime.Now; Itemlist.add (item); Log.info ("UploadFile", "enter 03"); ItemList return; #endregion #region Upload file-file information will be saved to the database.//<summary> 65/ Upload file-file information will be saved to database///</summary>//<returns></returns> [HttpPost] 6 9 [Route ("Uploadfiletoserver")] PUblic Ihttpactionresult Uploadfiletoserver () 71 {72//verify is Multipart/form-data if (!r Equest. Content.ismimemultipartcontent ("Form-data")) the new Httpresponseexception (request.c Reateresponse (Httpstatuscode.unsupportedmediatype)); list<attachmentdto> List = new list<attachmentdto> (); DevId string = ""; (int i = 0; i < HttpContext.Current.Request.Files.Count; i++) Bayi { Tppostedfile file = Httpcontext.current.request.files[i]; sFileName string = "St_m_" + guid.newguid () + System.IO.Path.GetExtension (file. FileName); AppDomain.CurrentDomain.BaseDirectory string path = + Serveruploadfolder + "/"; The file. SaveAs (Path.Combine (Path, sfilename)); Attachmentdto entity = new Attachmentdto (); DevId = HttpconText. current.request["DevId"]. ToString (); Foreignid string = httpcontext.current.request["Foreignid"]. ToString (); The entity. Foreignid = Foreignid; 94 entity. FileName = sFileName; The entity. FilePath = Serveruploadfolder; The entity. Uploadtime = DateTime.Now; The entity. ContentType = file. ContentType; 98 entity. FileSize = file. ContentLength; The entity. Createdtime = datetime.now;100 101 list. ADD (Entity), 102}103 104 mobilebl.getinstance (). Insertattachment (devId, list); return Ok (True) 106}107 #endregion108}109 public C Lass renamingmultipartformdatastreamprovider:multipartformdatastreamprovider110 {111 public string Root {ge T Set }112//public Func<fileupload.postedfile, string> ongetlocalfilename {get; set;} 113 RenamingmultiparTformdatastreamprovider (String root) 115:base (root), 117 root = root;118}119 + public override string Getlocalfilename (Httpcontentheaders headers) 121 {122 string Filepat h = headers. Contentdisposition.filename;123 124//Multipart requests with the file name seem to always include quotes.125 if (Filepath.startswith (@ "" ") && Filepath.endswith (@" "" ") 126 FilePath = filepath.su Bstring (1, filepath.length-2); 127 var filename = path.getfilename (filePath); 129 var Extensio n = path.getextension (FilePath); var contentType = headers. contenttype.mediatype;131 "St_m_" + guid.newguid () + extension;133}134 135}
Android studiod code Download: Click to download
Reference: http://www.cnblogs.com/fly100/articles/3492525.html
Android Implementation form submission, WEBAPI receive