1. 程式人生 > >Post同時上傳多張圖片和資料例項

Post同時上傳多張圖片和資料例項

1.通過http協議,post同時上傳多張圖片和資料到伺服器上。
2.IOS開發中前端採用xcode 7.1 swift語言。
3.伺服器端採用asp.net,asp實現。

一、下面先看看前端程式碼。
1.先把需要上傳的圖片存在img陣列中。
2.imgs為圖片數量,names和context為需要上傳的資料。
上傳圖片swift程式碼:

 func upload(img:[UIImage])
     {
        let context = mytext.text
        let names : String = self.title! as String
        lb.frame
=CGRectMake(0,250, self.view.bounds.size.width,20) lb.textColor=UIColor.whiteColor() lb.text="上傳中...." lb.textAlignment=NSTextAlignment.Center lb.backgroundColor=UIColor.blackColor() lb.alpha=1 //新增風火輪 av.frame=CGRectMake(100,280,20, 20) av.backgroundColor
=UIColor.whiteColor() av.color=UIColor.redColor() av.startAnimating() self.view.addSubview(av) self.view.addSubview(lb) var data:[NSData] = [UIImagePNGRepresentation(img[0])!] for (var i = 1; i < imgs; ++i) { data += [UIImagePNGRepresentation(img[i])! as NSData] } let uploadurl:String="http://192.168.2.66:81/uploadpic.aspx?id="
+names+"&context="+context //設定伺服器接收地址 let request=NSMutableURLRequest(URL:NSURL(string: uploadurl)!) request.HTTPMethod="POST"//設定請求方式 let body=NSMutableData() let boundary:String="---------------------------7d33a816d302b6" let contentType:String="multipart/form-data;boundary="+boundary request.addValue(contentType, forHTTPHeaderField:"Content-Type") //傳圖片 for (var k = 0; k < imgs; ++k) { body.appendData(NSString(format:"\r\n--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format:"Content-Disposition:form-data;name=\"userfile1\";filename=\"dd1.jpg\"\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format:"Content-Type:image/jpeg\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(data[k]) } body.appendData(NSString(format:"\r\n--\(boundary)--\r\n").dataUsingEncoding(NSUTF8StringEncoding)!) request.HTTPBody=body let que=NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request, queue: que, completionHandler: { (Response, data, error) -> Void in if (error != nil){ print(error) }else{ let tr:String=NSString(data:data!,encoding:NSUTF8StringEncoding)! as String print(tr) //在主執行緒中更新UI風火輪才停止 dispatch_sync(dispatch_get_main_queue(), { self.av.stopAnimating() self.lb.hidden=true }) } }) }

二、伺服器端實現程式碼。
1、資料庫,用來儲存上傳的資料和圖片路徑。
context(
[ID] [int] IDENTITY(1,1) NOT NULL,
[nosn] varchar NULL,
[context] varchar NULL,
[createtime] varchar NULL,
[img1] varchar NULL,
[img2] varchar NULL,
[img3] varchar NULL,
[img4] varchar NULL

2、接收上傳多張圖片的程式碼:uploadpic.aspx

<%@ Page language="c#" AutoEventWireup="false"  %> 
<%
string names = Request.QueryString["id"];
string ctxt = Request.QueryString["context"];
string spath = Server.MapPath("/"+names);
string SaveFilePath ="";
string[] sfpath =new string[4];
int rq = Request.Files.Count;
Response.Write(rq);
if (System.IO.Directory.Exists(spath) == false)
{
System.IO.DirectoryInfo dirinfo = System.IO.Directory.CreateDirectory(spath);
}
int i=0;
for (i=0; i<=rq-1; i++ ) {
    sfpath[i] = "/"+names+"/"+System.DateTime.Now.ToString("yyyymmddhhmmssfff") + i+".jpg";
 SaveFilePath = Server.MapPath(sfpath[i]);
HttpPostedFile postfile1=Request.Files[i];
postfile1.SaveAs(SaveFilePath);
}
Response.Write(rq + "  image upload success!\r\n");
string url = "http://192.168.2.66:81/postcontext.asp?id="+ names + "&context=" + ctxt + "&img1="+sfpath[0] +"&img2="+sfpath[1] +"&img3="+sfpath[2] +"&img4="+sfpath[3];
//string data = "id="+ names + "&context=" + ctxt + "&img1="+sfpath1 +"&img2="+sfpath2 +"&img3="+sfpath3 +"&img4="+sfpath4;
string data = "";
Response.Write (data);
 try
{
byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(data);
System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "text/html";
myRequest.ContentLength = postBytes.Length;
myRequest.Proxy = null;
System.IO.Stream newStream = myRequest.GetRequestStream();
newStream.Write(postBytes, 0, postBytes.Length);
newStream.Close();
// Get response
System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)myRequest.GetResponse();
using (System.IO.StreamReader reader = new System.IO.StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
string content = reader.ReadToEnd();
Response.Write( content);
}
}
catch (System.Exception ex)
{
Response.Write( ex.Message);
}
 Response.End();
%>

3.儲存資料的檔案:postcontext.asp

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!-- #include file="conn.asp" --> 
<%
dim id,mys
urls="http://192.168.2.66:81"
id = Request.QueryString("id")

mys = request.QueryString("context")
img1 = request.QueryString("img1")
img2 = request.QueryString("img2")
img3 = request.QueryString("img3")
img4 = request.QueryString("img4")
if img1<> "" then
   img1 = urls & img1
 end if 

if img2<> "" then
   img2 = urls & img2
 end if 
 if img3<> "" then
   img3 = urls & img3
 end if 
 if img4<> "" then
   img4 = urls & img4
 end if 
 dim rs1
sqlcmd="insert into context (nosn,context,createtime,img1,img2,img3,img4) VALUES  ('"&id&"','"&mys&"',getdate(),'"&img1&"','"&img2&"','"&img3&"','"&img4&"') "
set rs1=conn.execute(sqlcmd)  
response.Write(sqlcmd)
Response.write "儲存成功!"
  %>