最近工作中用到了一種使用JS+form用post方式上傳文件一種方式。前臺(tái)用Html input,使用JS方式往服務(wù)器上傳文件,具體實(shí)現(xiàn)看代碼:
前臺(tái)頁(yè)面使用aspx網(wǎng)頁(yè),使用input 標(biāo)簽,用其file類型;此標(biāo)簽不使用runat="server".不使用服務(wù)器控件;這里需要加上一個(gè)iframe標(biāo)簽。并隱藏;設(shè)置一a標(biāo)簽。用來(lái)作為用戶點(diǎn)擊按鈕;調(diào)用JS函數(shù):Uploadfun();
1
2
3
4
5
|
< div > < input type = "file" id = "FileUpLoad" name = "FileUpLoad" style = "width:140px;" /> < a href = "javascript:void(0);" rel = "external nofollow" onclick = "Uploadfun()" >上傳</ a > < iframe name = "hidden_frame" id = "hidden_frame" style = "width:10%;display:none;" ></ iframe > </ div > |
JS代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
function Uploadfun(){ var _file = document.getElementById( "FileUpLoad" ); //此處是前臺(tái)頁(yè)面的 input 標(biāo)簽的ID var _form = document.createElenent( "form" ); //創(chuàng)建一個(gè)form document.body.appendChild(_form); //添加一個(gè)form _form.encoding = "multipart/form-data" ; //使用該編碼規(guī)程可以不限制 post表單2M大小的限制 _form.method= "post" ; //使用POST方式 _form.action= "../Service/FileSrv.aspx?Type=Client&CallFun=UploadFile" ; //此處使用Get方式,傳到前臺(tái)頁(yè)面的后臺(tái)Server代碼層; // 這個(gè)是本人工作中的項(xiàng)目位置 _form.target = "hidden_frame" ; var pos = _file.nextSibling; _form.appendChild(_file); _form.submit(); pos.parentNode.insertBefore(_file,pos); document.body.renoveChild(_form); } |
C#層代碼:就是JS代碼中的form的action的所標(biāo)識(shí)。在FileSrv.aspx的后臺(tái)cs代碼中,我們可以通過(guò)使用getquery
方法,得到使用Get方式傳過(guò)來(lái)的參數(shù);
這個(gè)例子里參數(shù)Type=Client是一個(gè)模塊標(biāo)識(shí),CallFun則是指出cs代碼層要調(diào)用的響應(yīng)函數(shù);UploadFile();
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
private void UploadFile() { // //......其他代碼 // HttpFileCollection files = HttpContext.Current.Request.Files; if (files.Count>0) { int lintTemp = files[0].FileName.LastIndexOf( "." ); //得到input標(biāo)簽中的file文件路徑; string lstrFileType = string .Empty; string lstrContentType = string .Empty; if (lintTemp!=-1 &&files[0].FileName.Length>lintTemp+1) { lstrFileType = files[0].FileName.Substring(lintTemp+1).ToUpper(); } if (lstrFileType.ToUpper()== "JPG" ) { if (files[0].ContentLength<10485760) { //記得要先保存到應(yīng)用程序發(fā)布所在的服務(wù)器上! files[0].SaveAs(Server.MapPath( "~/Files/" )+ "JPG1." +files[0].FileName.Substring(files[0].FileName.LastIndexOf( "." ))); } } } // //......其他代碼 // } |
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/chenqiangdage/article/details/20225027