客户端一:下面为 Android 客户端的实现代码:

/***android上传文件到服务器**下面为httppost报文格式*POST/logsys/home/uploadIspeedLog!doDefault.htmlHTTP/1.1  Accept:text/plain,  Accept-Language:zh-cn  Host:192.168.24.56  Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2  User-Agent:WinHttpClient  Content-Length:3693  Connection:Keep-Alive注:上面为报文头  -------------------------------7db372eb000e2  Content-Disposition:form-data;name="file";filename="kn.jpg"  Content-Type:image/jpeg  (此处省略jpeg文件二进制数据...)  -------------------------------7db372eb000e2--**@parampicPaths*需要上传的文件路径集合*@paramrequestURL*请求的url*@return返回响应的内容*/publicstaticStringuploadFile(String[]picPaths,StringrequestURL){Stringboundary=UUID.randomUUID().toString();//边界标识随机生成Stringprefix="--",end="\r\n";Stringcontent_type="multipart/form-data";//内容类型StringCHARSET="utf-8";//设置编码intTIME_OUT=10*10000000;//超时时间try{URLurl=newURL(requestURL);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setReadTimeout(TIME_OUT);conn.setConnectTimeout(TIME_OUT);conn.setDoInput(true);//允许输入流conn.setDoOutput(true);//允许输出流conn.setUseCaches(false);//不允许使用缓存conn.setRequestMethod("POST");//请求方式conn.setRequestProperty("Charset","utf-8");//设置编码conn.setRequestProperty("connection","keep-alive");conn.setRequestProperty("Content-Type",content_type+";boundary="+boundary);/***当文件不为空,把文件包装并且上传*/OutputStreamoutputSteam=conn.getOutputStream();DataOutputStreamdos=newDataOutputStream(outputSteam);StringBufferstringBuffer=newStringBuffer();stringBuffer.append(prefix);stringBuffer.append(boundary);stringBuffer.append(end);dos.write(stringBuffer.toString().getBytes());Stringname="userName";dos.writeBytes("Content-Disposition:form-data;name=\""+name+"\""+end);dos.writeBytes(end);dos.writeBytes("zhangSan");dos.writeBytes(end);for(inti=0;i<picPaths.length;i++){Filefile=newFile(picPaths[i]);StringBuffersb=newStringBuffer();sb.append(prefix);sb.append(boundary);sb.append(end);/***这里重点注意:name里面的值为服务器端需要key只有这个key才可以得到对应的文件*filename是文件的名字,包含后缀名的比如:abc.png*/sb.append("Content-Disposition:form-data;name=\""+i+"\";filename=\""+file.getName()+"\""+end);sb.append("Content-Type:application/octet-stream;charset="+CHARSET+end);sb.append(end);dos.write(sb.toString().getBytes());InputStreamis=newFileInputStream(file);byte[]bytes=newbyte[8192];//8kintlen=0;while((len=is.read(bytes))!=-1){dos.write(bytes,0,len);}is.close();dos.write(end.getBytes());//一个文件结束标志}byte[]end_data=(prefix+boundary+prefix+end).getBytes();//结束http流dos.write(end_data);dos.flush();/***获取响应码200=成功当响应成功,获取响应的流*/intres=conn.getResponseCode();Log.e("TAG","responsecode:"+res);if(res==200){returnSUCCESS;}}catch(MalformedURLExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}returnFAILURE;}

服务端一:下面为 Java Web 服务端 servlet 的实现代码:

publicclassFileImageUploadServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;privateServletFileUploadupload;privatefinallongMAXSize=4194304*2L;//4*2MBprivateStringfiledir=null;/***@seeHttpServlet#HttpServlet()*/publicFileImageUploadServlet(){super();//TODOAuto-generatedconstructorstub}/***设置文件上传的初始化信息**@seeServlet#init(ServletConfig)*/publicvoidinit(ServletConfigconfig)throwsServletException{FileItemFactoryfactory=newDiskFileItemFactory();//Createafactory//fordisk-based//fileitemsthis.upload=newServletFileUpload(factory);//Createanewfileupload//handlerthis.upload.setSizeMax(this.MAXSize);//Setoverallrequestsize//constraint4194304filedir=config.getServletContext().getRealPath("images");System.out.println("filedir="+filedir);}/***@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponse*response)*/@SuppressWarnings("unchecked")protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{//TODOAuto-generatedmethodstubPrintWriterout=response.getWriter();try{//StringuserName=request.getParameter("userName");//获取form//System.out.println(userName);List<FileItem>items=this.upload.parseRequest(request);if(items!=null&&!items.isEmpty()){for(FileItemfileItem:items){Stringfilename=fileItem.getName();if(filename==null){//说明获取到的可能为表单数据,为表单数据时要自己读取InputStreamformInputStream=fileItem.getInputStream();BufferedReaderformBr=newBufferedReader(newInputStreamReader(formInputStream));StringBuffersb=newStringBuffer();Stringline=null;while((line=formBr.readLine())!=null){sb.append(line);}StringuserName=sb.toString();System.out.println("姓名为:"+userName);continue;}Stringfilepath=filedir+File.separator+filename;System.out.println("文件保存路径为:"+filepath);Filefile=newFile(filepath);InputStreaminputSteam=fileItem.getInputStream();BufferedInputStreamfis=newBufferedInputStream(inputSteam);FileOutputStreamfos=newFileOutputStream(file);intf;while((f=fis.read())!=-1){fos.write(f);}fos.flush();fos.close();fis.close();inputSteam.close();System.out.println("文件:"+filename+"上传成功!");}}System.out.println("上传文件成功!");out.write("上传文件成功!");}catch(FileUploadExceptione){e.printStackTrace();out.write("上传文件失败:"+e.getMessage());}}}

客户端二:下面为用 .NET 作为客户端实现的 C# 代码:

/**下面为httppost报文格式POST/logsys/home/uploadIspeedLog!doDefault.htmlHTTP/1.1  Accept:text/plain,  Accept-Language:zh-cn  Host:192.168.24.56  Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2  User-Agent:WinHttpClient  Content-Length:3693  Connection:Keep-Alive注:上面为报文头  -------------------------------7db372eb000e2  Content-Disposition:form-data;name="file";filename="kn.jpg"  Content-Type:image/jpeg  (此处省略jpeg文件二进制数据...)  -------------------------------7db372eb000e2--***/privateSTATUSuploadImages(Stringuri){Stringboundary="------------Ij5ei4ae0ei4cH2ae0Ef1ei4Ij5gL6";;//边界标识Stringprefix="--",end="\r\n";/**根据uri创建WebRequest对象**/WebRequesthttpReq=WebRequest.Create(newUri(uri));httpReq.Method="POST";//方法名httpReq.Timeout=10*10000000;//超时时间httpReq.ContentType="multipart/form-data;boundary="+boundary;//数据类型/*******************************/try{/**第一个数据为form,名称为par,值为123*/StringBuilderstringBuilder=newStringBuilder();stringBuilder.Append(prefix);stringBuilder.Append(boundary);stringBuilder.Append(end);Stringname="userName";stringBuilder.Append("Content-Disposition:form-data;name=\""+name+"\""+end);stringBuilder.Append(end);stringBuilder.Append("zhangSan");stringBuilder.Append(end);/*******************************/Streamsteam=httpReq.GetRequestStream();//获取到请求流byte[]byte8=Encoding.UTF8.GetBytes(stringBuilder.ToString());//把form的数据以二进制流的形式写入steam.Write(byte8,0,byte8.Length);/**列出G:/images/文件夹下的所有文件**/DirectoryInfofileFolder=newDirectoryInfo("G:/images/");FileSystemInfo[]files=fileFolder.GetFileSystemInfos();for(inti=0;i<files.Length;i++)    {      FileInfofile=files[i]asFileInfo;stringBuilder.Clear();//清理stringBuilder.Append(prefix);stringBuilder.Append(boundary);stringBuilder.Append(end);/***这里重点注意:name里面的值为服务器端需要key只有这个key才可以得到对应的文件*filename是文件的名字,包含后缀名的比如:abc.png*/stringBuilder.Append("Content-Disposition:form-data;name=\""+i+"\";filename=\""+file.Name+"\""+end);stringBuilder.Append("Content-Type:application/octet-stream;charset=utf-8"+end);stringBuilder.Append(end);byte[]byte2=Encoding.UTF8.GetBytes(stringBuilder.ToString());steam.Write(byte2,0,byte2.Length);FileStreamfs=newFileStream(file.FullName,FileMode.Open,FileAccess.Read);//读入一个文件。BinaryReaderr=newBinaryReader(fs);//将读入的文件保存为二进制文件。intbufferLength=8192;//每次上传8k;byte[]buffer=newbyte[bufferLength];longoffset=0;//已上传的字节数intsize=r.Read(buffer,0,bufferLength);while(size>0){steam.Write(buffer,0,size);offset+=size;size=r.Read(buffer,0,bufferLength);}/**每个文件结束后有换行**/byte[]byteFileEnd=Encoding.UTF8.GetBytes(end);steam.Write(byteFileEnd,0,byteFileEnd.Length);fs.Close();r.Close();}byte[]byte1=Encoding.UTF8.GetBytes(prefix+boundary+prefix+end);//文件结束标志steam.Write(byte1,0,byte1.Length);steam.Close();WebResponseresponse=httpReq.GetResponse();//获取响应Console.WriteLine(((HttpWebResponse)response).StatusDescription);//显示状态steam=response.GetResponseStream();//获取从服务器返回的流StreamReaderreader=newStreamReader(steam);stringresponseFromServer=reader.ReadToEnd();//读取内容Console.WriteLine(responseFromServer);//清理流reader.Close();steam.Close();response.Close();returnSTATUS.SUCCESS;}catch(System.Exceptione){Console.WriteLine(e.ToString());returnSTATUS.FAILURE;}}

服务端二: 下面为 .NET 实现的服务端 C# 代码:

protectedvoidPage_Load(objectsender,EventArgse){stringuserName=Request.Form["userName"];//接收formHttpFileCollectionMyFilecollection=Request.Files;//接收文件for(inti=0;i<MyFilecollection.Count;i++){MyFilecollection[i].SaveAs(Server.MapPath("~/netUploadImages/"+MyFilecollection[i].FileName));//保存图片}}

更多相关文章

  1. 在Android中实现文件读写
  2. Android里解析AndroidManifest.xml的java文件
  3. android 文件系统结构及其引导
  4. Android中彩信文件的读取
  5. Android 上传图片到服务器(多文件上传)
  6. Android 系统文件简介
  7. Android 保存数据到文件
  8. Android 使用FTP上传文件

随机推荐

  1. 参考:修改android开机界面
  2. Android实战——Mp3播放器
  3. Android(安卓)ART Hook 实现 - SandHook
  4. Android(安卓)Intent学习笔记
  5. Android中String资源文件的String.format
  6. Android Handler 消息机制
  7. 【Android 性能优化】应用启动优化 ( 安
  8. 史上最详细的Android系统SystemUI 启动过
  9. Kotlin 概览——如何看待 Google 将 Kotl
  10. [Android] [ Android启动流程 ] [ 下 ] [