C # Implement multi-file uploads, write to folders, get file information and download files and delete files

Source: Internet
Author: User

Front desk:. js

//Uploading Attachmentsfunctionuploadattachment () {if($ ("#Tipbind"). attr (' checked ')) {        varIP = $ ("#TunBandIP"). Val (); if($.trim (IP) = = 0) {            return$.messager.show ({title: ' Hint ', msg: ' Please select IP First ' }); }        $(' #ImprotDlg '). Dialog (' Open '));        Uploadfy (IP); $("#T_ExcelName"). Val (""); $("#T_SheetName"). Val (""); }    Else{$.messager.show ({title:' Hint ', msg: ' Only the bound IP can upload attachments ' }); }}varOnComplete =false;functionuploadfy (IP) {$ ("#uploadify"). uploadify ({' swf ': '/scripts/uploadify/uploadify.swf ',        ' Uploader ': '/ajaxterminalinfo/uploadattachments.cspx ',        ' FormData ': {' IP ': IP},' Folder ': '/attachments ',        ' Queueid ': ' Filequeue ',        ' method ': ' Get ',        ' Auto ':false,        ' SizeLimit ': 20480000,        ' Multi ':true,        ' Filedesc ': ' Please select File ',        ' Fileext ': ' * ',        ' Width ': 110,        ' Height ': 28,        ' ButtonText ': ' Please select File ',        ' Scriptdata ': {},        ' OnSelect ':function(E, Queueid, fileobj) {qId=Queueid; },        ' Onuploadsuccess ':function(file, data, response) {vardatamsg = eval ("val= (" + Data + ")"); if(datamsg. Success) {$.messager.show ({title:Prompted, Msg:datamsg.                Success}); $(' #ImprotDlg '). Dialog (' Close '); } Else{$.messager.show ({title:Prompted, Msg:datamsg.            Error}); } oncomplete=true; },        ' Onuploaderror ':function(file, ErrorCode, ErrorMsg, errorstring) {if(File.size > 20480000{$.messager.show ({title:' Hint ', msg: ' Upload file cannot exceed 20M ' }); }        },        ' OnCancel ':function(file) {}});//Start uploadingfunctionUploadFile () {varFileName = $ ("#T_ExcelName"). Val (); if(filename = = ""{$.messager.show ({title:' Hint ', msg: ' Please select Upload file! ‘ }); return; }    $(' #uploadify '). Uploadify (' upload ', ' * '));}//Cancel UploadfunctionCanceluploadfile () {$ (' #uploadify '). Uploadify (' Cancel ', ' * '); $(' #ImprotDlg '). Dialog (' Close ');}//View Attachmentsfunctionshowattachment () {varIP = $ ("#TunBandIP"). Val (); if($.trim (IP) = = 0) {        return$.messager.show ({title: ' Hint ', msg: ' Please select IP First ' }); }    $("#attachmentDlg"). Dialog (' Open '); varDgobj ={queryparams: {ip:ip}, Singleselect:true, URL:'/ajaxterminalinfo/getattachmentsbyip.cspx ', Method:' Get ', border:false, toolbar: [{text:Download, Iconcls:' Icon-import ', Handler:function () {                varRow = $ ("#dg"). DataGrid (' getchecked '); if(Row.length = = 0) {                    return$.messager.show ({title: ' Hint ', msg: ' Please select file to download First ') }); }                 for(vari = 0; i < row.length; i++) {                    $(' #attachmentForm '). attr (' action ', '/ajaxterminalinfo/downloadattachment.cspx?filepath= ' + row[i]. FilePath + "&filename=" +Row[i].                    FileName); $(' #attachmentForm '). Submit (); }}}, {text:Delete, Iconcls:' Icon-no ', Handler:function() {alert (1)}}], columns: [[{field:' CK ', checkbox:true}, {field:' filename ', title: ' filename ', width:310, align: ' left ', halign: ' Center '}, {field:' Uploaddatetime ', title: ' Upload Date ', width:120, align: ' center ' }        ]]    }; $("#dg"). DataGrid (Dgobj);}

<summary>
deleting files
</summary>
<param name= "filepath" ></param>
<param name= "filename" ></param>
<returns></returns>
[Action]
[SessionMode (Sessionmode.support)]
Public Object deleteattachment (string filepath, string filename)
{
Message message = new Message ();
Try
{
Judging if the file is not present
if (file.exists (filepath))
{
Delete if it exists
File.delete (filepath);
Message. Success = "Delete file succeeded";
Message.data = true;
}
Else
{
Message. Success = "File does not exist";
Message.data = false;
}
return jsonconvert.serializeobject (message);
}
catch (Exception e)
{
Log. Debug ("Cause of Error:" + e.message);
Message. Error = "Delete file failed:" + e.message;
Message.data = false;
return jsonconvert.serializeobject (message);
}
}

Backstage:. CS

/// <summary>        ///Uploading Attachments/// </summary>        /// <returns></returns>[Action] [SessionMode (sessionmode.support)] Public Objectuploadattachments () {varMessage =NewMessage (); Try{httppostedfile file= httpcontext.current.request.files["Filedata"]; varIP = httpcontext.current.request.params["IP"]; stringPath ="/attachments/"+ IP +"/";//relative Path                if(File! =NULL&& file. ContentLength >0)                {                    stringSavepath =Path.Combine (HttpContext.Current.Server.MapPath (Path)); if(!directory.exists (Savepath))                    Directory.CreateDirectory (Savepath); File. SaveAs (Savepath+file.                    FileName); Message. Success="Upload Successful"; }                Else{message.} Error="the file cannot be empty"; }            }            Catch(Exception e) {log. Debug ("cause of error:"+e.message); Message. Error="cause of error:"+E.message; Throw; }            returnjsonconvert.serializeobject (message); }        /// <summary>        ///         /// </summary>        /// <returns></returns>[Action] [SessionMode (sessionmode.support)] Public ObjectGetattachmentsbyip (stringIP) {            Try            {                stringPath ="/attachments/"+ IP +"/";//relative Path                stringSavepath =Path.Combine (HttpContext.Current.Server.MapPath (Path)); varDgdata =NewDatagriddata<diyfile>(); string[] FileNames =Directory.GetFiles (Savepath); foreach(varFileNameinchfileNames) {                    varfi =NewFileInfo (fileName); varFileInfo =NewDiyfile (); FileInfo. FileName=fi.                    Name; FileInfo. FilePath=FileName; FileInfo. Uploaddatetime=fi.                    LastAccessTime;                DGDATA.ROWS.ADD (FileInfo); } dgdata.total=Filenames.count (); varDgjson =Jsonconvert.serializeobject (Dgdata); returnDgjson; }            Catch(Exception e) {log. Debug ("cause of error:"+e.message); Throw; }} [Action] [SessionMode (sessionmode.support)] Public voidDownloadattachment (stringFilePathstringfilename) {            Try            {                using(varFS =NewFileStream (filepath, FileMode.OpenOrCreate)) {                    varbytes =New byte[(int) fs.                    Length]; Fs. Read (Bytes,0, Bytes.                    Length); Fs.                    Close ();                    HttpContext.Current.Response.Clear (); HttpContext.Current.Response.ContentType="Application/octet-stream"; //notifies the browser to download a file instead of opening itHttpContext.Current.Response.AddHeader ("content-disposition","attachment; Filename="+httputility.urlencode (filename, Encoding.UTF8));                    HttpContext.Current.Response.BinaryWrite (bytes);                    HttpContext.Current.Response.Flush (); Fs.                Close (); }            }            Catch(Exception e) {log. Debug ("cause of error:"+e.message); Throw; }        }

C # Implement multi-file uploads, write to folders, get file information and download files and delete files

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.