Asp.net + js implements code for parsing csv files without refreshing new uploads

Source: Internet
Author: User

Some time ago, I used it in my work. I pasted the code and only kept the relevant code. I found that there were very few codes.
Upload page html/js
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Script type = "text/javascript">
Function FinishUpload (filePath ){
Document. getElementById ("uploadForm"). reset ();
If (! FilePath ){
Alert ("Import Failed! ");
}
Else {
Alert ("Imported Successfully to" + decodeURIComponent (filePath) + "! ");
}
}
Function UploadFile (){
Var arr = document. getElementById ("txtFile"). value. split ('.');
Var fileType = arr [arr. length-1];
If (fileType. toLowerCase (). indexOf ("csv") <0 ){
Document. getElementById ("uploadForm"). reset ();
Alert ("Please select a csv file .");
Return false;
}
Document. getElementById ("uploadForm"). encoding = "multipart/form-data ";
Document. getElementById ("uploadForm"). submit ();
}
Function ResetFile (file ){
Var tmpForm = document. createElement ('form ');
File. parentNode. insertBefore (tmpForm, file );
TmpForm. appendChild (file );
TmpForm. reset ();
TmpForm. removeNode (false );
}
</Script>
</Head>
<Body>
<Form id = "uploadForm" name = "uploadForm" action = "Upload. ashx" method = "post" target = "hidIframe" enctype = "multipart/form-data">
<Table cellpadding = '0' cellspacing = '0' style = "width: 100%; height: 100%; border-collapse: collapse;" border = "0">
<Tr>
<Td>
<Input id = "txtFile" name = "txtFile" type = "file" style = "border: solid 1px Gray;"/>
<Iframe name = "hidIframe" id = "hidIframe" style = "display: none;"> </iframe>
</Td>
</Tr>
<Tr>
<Td>
<Input type = "button" id = "btnImportOK" value = "Upload" onclick = "UploadFile ();"/>
<Input type = "button" id = "btnImportCancel" onclick = "ResetFile (document. getElementById ('txtfile')" value = "Reset"/>
</Td>
</Tr>
</Table>
</Form>
</Body>
</Html>

 
Process File Upload c #
Copy codeThe Code is as follows:
If (context. Request. Files. Count> 0)
{
HttpPostedFile file = context. Request. Files [0];
If (file. ContentLength> 0)
{
String title = string. Empty;
Title = DateTime. Now. ToString ("yyyyMMddHHmmss") + "_" + Path. GetFileName (file. FileName );
String path = "./Upload/" + title;
Path = System. Web. HttpContext. Current. Server. MapPath (path );
File. SaveAs (path );
Context. Response. Write ("<script> window. parent. FinishUpload ('" + HttpUtility. UrlEncode (path) + "'); </script> ");
}
}
Else
{
Context. Response. Write ("<script> window. parent. FinishUpload (''); </script> ");
}

The basic principle is to submit a form to the iframe so that the refresh occurs in the iframe. Form sets action to point to the file to be uploaded, and target to iframe. The upload operation result can be returned to iframe. The FinishUpload method of the parent object is called to check whether the upload is successful. Therefore, this method is often used to disguise the unrefreshed effect when AJAX is not popular. It can still be used now.
Note that:
Enctype = "multipart/form-data" is indispensable. The default enctype encoding is "application/x-www-form-urlencoded" and enctype = "multipart/form-data ", used to upload files in binary mode.
To prevent file name garbled characters and prevent errors in the transmission of messy characters URLs, return the HttpUtility. UrlEncode when the file name is returned to the foreground, and decodeURIComponent when the file name is obtained in foreground JS.
When resetting the file selection box, you need to temporarily Insert the file selection box to the temporary form and reset it through the reset method of the form.
By the way, paste the code for parsing the uploaded csv file
Parse csv files
Copy codeThe Code is as follows:
Private DataTable importable (string filepath)
{
DataTable mydt = new DataTable ("myTableName ");
Mydt. Columns. Add ("Data ID", System. Type. GetType ("System. String "));
Mydt. Columns. Add ("Field Name", System. Type. GetType ("System. String "));
Mydt. Columns. Add ("New Value", System. Type. GetType ("System. String "));
DataRow mydr;
Using (System. IO. StreamReader mysr = new System. IO. StreamReader (filepath ))
{
Int data;
Char current;
StringBuilder text = new StringBuilder ();
IDictionary <int, List <string> results = new Dictionary <int, List <string> ();
Bool isInYinHao = false ;;
Int lineId = 1;
Int index = 0;
While (true)
{
Data = mysr. Read ();
If (data! =-1)
{
Current = (char) data;
If (current = '"')
{
If (isInYinHao)
{
IsInYinHao = false;
}
Else
{
If (index> 0)
{
Text. Append (current );
}
IsInYinHao = true;
}
}
Else if (current = ',')
{
If (isInYinHao)
{
Text. Append (current );
}
Else
{
SaveResult (results, lineId, text );
Index = 0;
Continue;
}
}
Else if (current = '\ R ')
{
If (isInYinHao)
{
Text. Append (current );
}
}
Else if (current = '\ n ')
{
If (isInYinHao)
{
Text. Append (current );
}
Else
{
SaveResult (results, lineId, text );
Index = 0;
LineId ++;
Continue;
}
}
Else if (current = '\ 0 ')
{
}
Else
{
Text. Append (current );
}
Index ++;
}
Else
{
// Read to file end.
SaveResult (results, lineId, text );
Break;
}
}
Foreach (int id in results. Keys)
{
Mydr = mydt. NewRow ();
For (int I = 0; I <results [id]. Count; I ++)
{
If (I> 2)
{
Break;
}
Mydr [I] = results [id] [I];
}
Mydt. Rows. Add (mydr );
}
}
Return mydt;
}
Private void SaveResult (IDictionary <int, List <string> results, int lineId, StringBuilder text)
{
If (! Results. ContainsKey (lineId ))
{
Results. Add (lineId, new List <string> ());
}
Results [lineId]. Add (text. ToString ());
Text. Remove (0, text. Length );
}

Click to download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.