How do I add support for FTP uploads and previews in the Attachment management module?

Source: Internet
Author: User
Tags ftp file ftp client
In the previous introduction of the Attachment Management module "WinForm Development framework of the General Annex management module" and "WinForm development framework of the Attachment Management application", introduced the attachment management function, through the database records processing and file management, to achieve the attachment file and records of integrated management, Can be used in a standalone version of the WinForm framework, but also in a distributed hybrid development framework, with some development scenarios rich, we need to upload files in FTP, so the Attachment management module to expand to fit more real project needs.

1, FTP upload, HTTP file preview implementation ideas

We envision an attachment management that needs to be reused on the WinForm, web and other development projects, so the underlying design needs to consider the corresponding processing, and later can be integrated with the WinForm HTML edit control, or the HTML edit control of the Web, Attachments are implemented uniformly within a single component.

With the help of FTP file upload, our stand-alone version or LAN-based WinForm interface program can also build an FTP server to realize file sharing, while distributed hybrid development framework, for file upload, can choose Service-based file system to write, It can also be uploaded on an FTP-based basis.

The logical relationship for uploading files based on the hybrid framework FTP is as follows.

After the file system is uploaded by FTP, we set up an HTTP service in the file system, so that the corresponding HTTP address can be downloaded, and the image is viewed and so on (can be implemented in the HTML editor).

2, the introduction of FTP components to achieve file upload

Using FTP upload, although in their own common class library has the Ftphelper class can be used, but relatively speaking, I prefer to introduce more sophisticated and powerful FTP open source components for related processing, here we use fluentftp this component (GitHub address:), This is a very versatile and powerful FTP component.

Fluentftp is a foreign-developed FTP-based, FTP-FTPS Library of. NET, Fluentftp is a fully managed FTP client that is designed to be easy to use and easy to extend. It supports a list of files and directories, uploads and downloads files and SSL/TLS connections. It can connect to UNIX and Windows IIS to establish an FTP server. This project is fully developed by managed C #.

Use the code for this component, paste it here, so that the overall has an intuitive understanding of it.

Create an FTP clientftpclient client = new FtpClient ("123.123.123.123");//If you don ' t specify login credentials, we u Se the "anonymous" user accountclient. Credentials = new NetworkCredential ("David", "pass123");//Begin connecting to the serverclient. Connect ();//Get a list of files and directories in the '/htdocs ' Folderforeach (Ftplistitem item in client. Getlisting ("/htdocs")) {//If this is a Fileif (item. Type = = Ftpfilesystemobjecttype.file) {//Get the File sizelong size = client. GetFileSize (item.            FullName); }//Get modified date/time of the file or folderdatetime time = client. Getmodifiedtime (item.    FullName); Calculate a hash for the file on the server side (default algorithm) Ftphash hash = client. Gethash (item.    FullName); }//Upload a fileclient. UploadFile (@ "C:\MyVideo.mp4", "/htdocs/big.txt");//Rename the uploaded fileclient. Rename ("/htdocs/big.txt", "/htdocs/big2.txt");//Download the file againclient. DownloadFile (@ "C:\MyVideo_2.mp4", "/HTDOcs/big2.txt ");//delete the fileclient. DeleteFile ("/htdocs/big2.txt");//delete a folder recursivelyclient. DeleteDirectory ("/htdocs/extras/");//Check if a file Existsif (client. FileExists ("/htdocs/big2.txt")) {}//Check if a folder existsif (client. DirectoryExists ("/htdocs/extras/")) {}//Upload a file and retry 3 times before giving Upclient. RetryAttempts = 3;client. UploadFile (@ "C:\MyVideo.mp4", "/htdocs/big.txt", Ftpexists.overwrite, False, ftpverify.retry);//disconnect! Good bye!client. Disconnect ();

With these understanding, we in the ordinary WinForm program or the hybrid framework of the program, we configure the specified FTP information, we can load this information in the code, FTP landing, file upload, download and other operations.

3, the Attachment management module realizes

With the above ideas and components of the auxiliary, we have the original Attachment management module for the relevant upgrade processing can be implemented in the FTP upload mode processing.

First, for convenience, we first define a configuration entity class that gets the FTP server, user name, password, and so on, as shown below.

    <summary>///FTP configuration information///</summary> [DataContract] [Serializable]public class Ftpinfo {//&lt ; summary>///default constructor///</summary>public Ftpinfo () {}///<summary>///parameterized constructor///</summary >///<param name= "Server" ></param>///<param name= "user" ></param>///<param name= " Password "></param>public ftpinfo (string server, string user, string password, string baseUrl) {this. Server = Server;this. User = User;this. Password = Password;this.        BASEURL = BASEURL; }///<summary>///FTP Service address//</summary> [Datamember]public string Server {get; set;} <summary>///FTP user name//</summary> [datamember]public string user {get; set;} <summary>///ftp Password//</summary> [Datamember]public string Password {get; set;} <summary>///the base path of the FTP, such as the path that can be specified as IIS:: 8000, easy to download open//</summary> [Datamember]public string BaseUrl { Get SeT }    }

Define a function that is specifically used to extract the relevant FTP parameters within the configuration file, as shown below.

        <summary>///gets the configured FTP configuration parameter///</summary>///<returns></returns>private FTPInfo Getftpconfig ()        {var ftp_server = config. Appconfigget ("Ftp_server"); var ftp_user = config. Appconfigget ("Ftp_user"); var ftp_pass = config. Appconfigget ("Ftp_password"); var ftp_baseurl = config. Appconfigget ("Ftp_baseurl"); return new Ftpinfo (Ftp_server, Ftp_user, Ftp_pass, Ftp_baseurl);        }

Where our configuration file is shown below.

The component code that uses FLUENTFTP is shown below.

Use FLUENTFTP to manipulate FTP files ftpclient client = new FtpClient (Ftpinfo.server, Ftpinfo.user, Ftpinfo.password);

The FTP component is then called to judge the directory, and none is created.

Determines the datetime directory (format: yyyy-mm) and does not exist to create string Savepath = String. Format ("/{0}-{1:d2}/{2}", DateTime.Now.Year, DateTime.Now.Month, category); bool Isexistdir = client. DirectoryExists (Savepath); if (!isexistdir) {    client. CreateDirectory (Savepath);}

Finally, upload the file with the component, upload the file here, because the previous Fileuploadinfo entity class is stored in a byte array, it is also the use of FTP components directly upload byte array.

Using FTP to upload files//Avoid file duplication, use the GUID named var ext = fileutil.getextension (info. FileName); var newfilename = string. Format ("{0}{1}", Guid.NewGuid (). ToString (), ext);//fileutil.getfilename (file); Savepath = Savepath.uricombine (newfilename); bool uploaded = client. Upload (info. FileData, Savepath, Ftpexists.overwrite, true);

Files uploaded to the file server, the rest is to store the relevant information into the data sheet of the Attachment management module, so that in use, directly use the information in the database, if it is necessary to view images or download files, then splicing the relevant HTTP address can be, Let's take a look at the corresponding database record as shown below.

With these basic information, we can simultaneously transform the WinForm HTML edit Control I introduced earlier: Zetahtmleditcontrol (share a WinForm inside the HTML edit controls zeta HTML editing control, Chinese-attached source) , I have all the English menus, toolbars, dialogs, prompting content and other resources in the culture, and in the toolbar to add the Insert Picture, printing function, the interface as shown below.

By default, the way we add images is definitely based on local files, but after we've modified the way we use FTP to upload files, we can get an HTTP address on the control to preview the image file.

This method constructs the image address, which belongs to the standard URL address, which can be viewed in various places, as shown in the following interface.

This is the Zetahtmleditcontrol control, the integration of our previous completed the FTP upload mode of the Attachment management module, the realization of the function of editing the online HTML, such HTML content, the same can be used in the Web interface of the HTML editor for display.

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.