Win Form + ASP. Web Service File upload download--hyappframe

Source: Internet
Author: User
Tags file url

This section explains how to upload the ASP. NET Web Service implementation file (with large files) on the Hyappframe server side, WinForm how the client downloads the file.

1 server-side file upload 1.1 upload file

The function FileUpload (Stringfilefullpath, byte[] file) is used to upload the file, check that the file path exists before the file is generated, and the folder is created first.

[WebMethod (enablesession = true,description = "Upload file")]public int FileUpload (string filefullpath,byte[] file) {   try< c1/>{       //Get folder       string dir = filefullpath.substring (0,filefullpath.lastindexof ("\ \"));       If the folder does not exist, create a folder if       (! Directory.Exists (dir))           directory.createdirectory (dir);       Write Files       file.writeallbytes (filefullpath, file);       return 1;    }   catch (Exception ex)    {       MyFuncLib.Log (ex. Message + "\ r \ n" + ex. StackTrace);       return-1;}    }
1.2 Merging files

After the experiment through the Web service upload file, if the size of more than 2M may encounter upload failure error, so the client processing upload large files, first split into small files, upload each, and then to the server merged into the original file.

[WebMethod (enablesession = true,description = "Merge file")]public int filemerge (string filefullpath,int num) {   try    {       int i = 0;       FileStream fs = new FileStream (Filefullpath, filemode.create,fileaccess.write);       while (num >= 0)       {           FileStream fssource = new FileStream (Filefullpath + i, filemode.open,fileaccess.read);           byte[] buffer = new Byte[fssource.length];           Fssource.read (buffer, 0, Convert.ToInt32 (fssource.length));           Fs. Write (buffer, 0, buffer. Length);           Fssource.close ();           num--;           i++;       }        Fs. Close ();       Delete temporary files       while (i >= 0)       {           File.delete (filefullpath + i);           i--;       }       return 1;    }   catch (Exception ex)    {       MyFuncLib.Log (ex. Message + "\ r \ n" + ex. StackTrace);        return-1;}    }
1.3 Deleting files

The function Filedelete (stringfilename) is used to delete a given file, to check whether the user is authenticated before deleting it, to check whether the given file path contains a special symbol, for example, if it contains two consecutive periods, the consumer tries to manipulate the file of the other path. Before deleting, also to determine whether the file exists, after the deletion to determine whether the file still exists, in order to determine whether the file is really deleted. Delete successfully returned 1, no files deleted returned 0.

[WebMethod (enablesession= true, Description = "Delete specified file")]publicint Filedelete (string fileName) {    try    {        if ( ! IsLogin ())            return-100;        FileName = Myfunclib.webdir +des. Decrypt (Filename,myfunclib.passwordkey);        Paths are not allowed to point to other directories        if (Filename.indexof ("..") >-1)            return 0;        If it is a folder, skip it and do not allow delete folder        if (directory.exists (fileName))            return 0;        If the file exists, delete the specified file if        (file.exists (filename))            file.delete (filename);        if (file.exists (fileName))            return 0;        else            return 1;    }    catch (Exception ex)    {        MyFuncLib.Log (ex. Message + "\ r \ n" + ex. StackTrace);        return-1;}    }
2 client File upload Download 2.1 File Upload

Upload files, support multiple selections, and sequentially process each file. When the size of the file to be processed exceeds 1M, it is segmented and uploaded sequentially, and then merged on the server when all the files are split. When the file is uploaded, the file name, storage path, size, type, associated record ID and other attributes should be stored in the database.

Privatevoid UploadFile () {try {this.progressBarX1.Value = 0;        This.progressBarX1.Minimum = 0;        String dirName = Sysparameters.webdir +webdir;        OpenFileDialog Ofg = Newopenfiledialog (); Ofg.        Title = "Select File"; Ofg.        Filter = "All Files |*.*"; Ofg.        FilterIndex = 1; Ofg.        Restoredirectory = true; Ofg.        MultiSelect = true; if (Ofg. ShowDialog () ==dialogresult.ok) {This.warningBox1.Text =string.            Empty; foreach (String FileName inofg. FileNames) {#region Process the upload file individually, string NewName =guid.newguid ().                ToString () + myfunclib.getfilenameext (fileName);                    using (FileStream fssource =new FileStream (FileName, FileMode.Open, FileAccess.Read)) {                    Read the source file into a bytearray.                    Long size =fssource.length; if (Size < int. MaxValue) this.progressBarX1.Maximum = (int) sizE else this.progressBarX1.Maximum = Int.                    MaxValue-1;                    int unit = 1024000; If the file volume is less than 1M, upload it once, if the file is larger than 1M, split upload if (size <= unit) {byte                        [] bytes = Newbyte[size];                        int numbytestoread = (int) size;                        int numbytesread = 0; while (numbytestoread> 0) {//Read could returnanything from 0 to NumB                            Ytestoread.                            int n =fssource.read (bytes, numbytesread, numbytestoread);                            Break when theend of the file is reached.                            if (n = = 0) break;                            Numbytesread + = n;                        Numbytestoread-=n; } numbytestoread =bytes.                        Length; Myfunclib.ws.                        FileUpload (dirName + newName, bytes);                    This.progressBarX1.Value = (int) size;  } else {//multiples int multiple = (int) (size                        /unit);                        remainder int residue = (int) (size-multiple* unit);                        int i = 0;                            while (multiple > 0) {byte[] bytes = Newbyte[unit];                            int numbytestoread= (int) unit;                            int numbytesread = 0;  while (Numbytestoread > 0) {//Read Mayreturn anything from 0                                To Numbytestoread.                                int n =fssource.read (bytes, numbytesread, numbytestoread);                                Break whenthe end of the file is reached.         if (n = = 0)                           Break                                Numbytesread +=n;                            numbytestoread-= N; } numbytestoread =bytes.                            Length;                            MyFuncLib.WS.FileUpload (dirName + newName + i, bytes);                            multiple--;                            i++;                        This.progressBarX1.Value = i * unit; } if (Residue > 0) {byte[] bytes = Newbyte[re                            Sidue];                            int numbytestoread= (int) residue;                            int numbytesread = 0;  while (Numbytestoread > 0) {//Read Mayreturn anything from 0                                To Numbytestoread.                                int n =fssource.read (bytes, numbytesread, numbytestoread); Break WHEnthe end of the file is reached.                                if (n = = 0) break;                                Numbytesread +=n;                            numbytestoread-= N; } numbytestoread =bytes.                            Length;                        MyFuncLib.WS.FileUpload (dirName + newName + i, bytes);                    }//merge files on the server MyFuncLib.WS.FileMerge (DirName + newName, i);                    } this.progressBarX1.Value = 0; Writes the successfully uploaded file to the database if (this.catename = = null) this.catename =string.                    Empty;                    String sql = "Insertinto core_attachment () VALUES ()";                    ArrayList sqlparams = Newarraylist ();                    ......                    Myfunclib.dbcommandexecnonequerybysql (SQL, sqlparams); This.warningBox1.Text = "" + fileName+ "" File has been uploaded "; } #endregion}}} catch (Exception ex) {Myfunclib.logtodb ("error", "System error", Ex. Message, ex.        StackTrace); Myfunclib.msg ("Select File encountered error," + ex.)    Message, "E"); }}
2.2 File Download

The function download (string URL, string path) is used to download the file. Given a file URL, download the file and provide support for the progress bar. Because the server side uses IIS to build, the ASP. NET Web Service provides services and is itself a Web site, so you can download the specified file on the server via a URL. to ensure server file security, there are two policies. The file path on the server is not easily guessed because the GUID is unique, irregular, and complex, so it is not easy to guess which files are listed in the file directory, and then the files uploaded to the server are renamed using the GUID.

Privatewebclient wc;privatevoid Download (string url, string path) {try {uri uri = new uri (URL);        WC = new WebClient (); Wc. Proxy = null;//Set the Internet agent as an empty WC.        downloadfilecompleted + = Newasynccompletedeventhandler (webclient_downloadfilecompleted); Wc.        DownloadProgressChanged + = Newdownloadprogresschangedeventhandler (webclient_downloadprogresschanged); Wc.        DownloadFileAsync (URI, path);    This.label1.Text = "Downloading file" "+ Oldname +" "; } catch (Exception ex) {myfunclib.msg ("Error: Connection Server failed," + ex. Message, "E");    }}privatevoid webclient_downloadprogresschanged (Object Sender,downloadprogresschangedeventargs e) { This.progressBarX1.Value =e.progresspercentage;}       Privatevoid webclient_downloadfilecompleted (object sender, AsyncCompletedEventArgs e) {try {//To open the specified file after download completes        System.Diagnostics.Process.Start (AppPath + oldname); This.    Close (); } catch (Exception ex) {myfunclib.msg ("Error: Open file failed," + ex. Message, "E"); }}

Win Form + ASP. Web Service File upload download--hyappframe

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.