Asp.net+js to achieve no refresh upload parse csv file code _javascript tips

Source: Internet
Author: User
Tags parse csv file urlencode
Used in the previous work, paste code, only to retain the relevant code to upload, found that the code is actually very few.
Upload page Html/js
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<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>
<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>

 
C # for processing file uploads
Copy Code code 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>");
}

Do not refresh, the basic principle is: through the form submitted to the IFRAME, so that the refresh occurred in the IFRAME. The form setting action points to the file that handles the upload, and target points to the IFRAME. The results of the upload operation can be returned to the IFRAME, calling the parent object's Finishupload method to show whether the upload succeeded. So when Ajax is not popular, this method is often used to disguise the effect of not refreshing, and can still be used now.
To be aware of:
Enctype= "Multipart/form-data" is not small, enctype the default encoding is "application/x-www-form-urlencoded", set enctype= "multipart/" Form-data ", used to upload files in binary mode.
In order to prevent the file name garbled, to prevent Chaos character URL delivery problems, return the file name to the foreground when the Httputility.urlencode, in the foreground JS to take the file name decodeURIComponent.
When you reset the file selection box, you temporarily insert the file selection box into the temporary form and reset it by using the form's Reset method.
By the way, it's code to parse the uploaded CSV file.
Parsing a CSV file
Copy Code code as follows:

Private DataTable importdatatable (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 = = ' ")
{
}
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.