Added support for FTP upload and preview in the attachment management module.
In the attachment management module described earlier, "Winform development framework-General attachment management module" and "Winform development framework-appendix management application" introduce the annex management function, through the processing of database records and file management, the integrated management of attachment files and records can be applied to the single-host WInform framework or distributed hybrid development framework, with the rich development scenarios, We need to upload files through FTP. Therefore, the attachment management module is extended to meet more actual project requirements.
1. How to Implement FTP upload and HTTP File Preview
The bottom layer of the proposed attachment management needs to be reused in development projects such as Winform and Web. Therefore, the corresponding processing needs to be considered for the underlying design, in addition, you can use the WInform HTML editing control or the Web HTML editing Control for integration. attachments are implemented in a single component.
With the help of FTP File Upload, we can build an FTP server separately for file sharing in a standalone version or LAN-based Winform interface program. In a distributed hybrid development framework, for file upload, you can choose to write data to the service-based file system, or upload data through FTP.
The logic of File Uploading based on a hybrid framework over FTP is as follows.
In this way, after the file system is uploaded through FTP, we build an HTTP service in the file system so that the corresponding HTTP address can download the file, and image viewing (which can be implemented in the HTML editor ).
2. Introduce the FTP component for File Upload
Although FTPHelper class is available in my own public class library, I prefer to introduce more powerful FTP open source components for related processing, here we use the FluentFTP component (GitHub address: https://github.com/hgupta9/FluentFTP), which is a very wide application, very powerful FTP component.
FluentFTP is A. Net-based FTP and ftps ftp class library developed by foreigners. FluentFTP is a fully-hosted FTP client designed for ease of use and scalability. It supports file and directory lists, upload and download files, and SSL/TLS connections. It can connect to Unix and Windows IIS to establish an FTP server. This project is fully developed and hosted C #.
The usage code of this component is pasted here for an intuitive understanding.
// create an FTP clientFtpClient client = new FtpClient("123.123.123.123");// if you don't specify login credentials, we use 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 file if (item.Type == FtpFileSystemObjectType.File){ // get the file size long size = client.GetFileSize(item.FullName); } // get modified date/time of the file or folder DateTime 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 this understanding, we can load the information in the Code by configuring the specified FTP information in a common Winform program or a hybrid framework program, FTP login, file upload, download, and other operations.
3. Attachment management module implementation
With the help of the above ideas and components, we can implement FTP upload mode by upgrading the original attachment management module.
First, for convenience, we first define a configuration entity class for obtaining FTP server, user name, password, and other parameters, as shown below.
/// <Summary> // FTP configuration information // </summary> [DataContract] [Serializable] public class FTPInfo {// <summary> // default Structure function // </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 Username // </summary> [DataMember] public string User {get; set ;} /// <summary> // FTP Password /// </summary> [DataMember] public string Password {get; set ;} /// <summary> /// FTP basic path. For example, you can specify it as the IIS path: http://www.iqidi.com:8000 To enable the download. /// </summary> [DataMember] public string BaseUrl {get; set ;}}
Define a function to extract the FTP parameters in the configuration file, as shown below.
/// <Summary> /// obtain the configured FTP configuration parameters /// </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 );}
The configuration file is as follows.
The component code of FluentFTP is as follows.
// Use FluentFTP to operate the FTP file FtpClient client = new FtpClient (ftpInfo. Server, ftpInfo. User, ftpInfo. Password );
Call the FTP component to determine the directory. If no directory exists, create one.
// Determine the date and time directory (Format: yyyy-MM). If the directory does not exist, 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, use the component to upload the file. Upload the file here. Because the FileUploadInfo object class previously stores byte arrays, you can directly upload byte Arrays Using the FTP component.
// Use FTP to upload files // avoid File Duplication. Use GUID to name 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 );
After a file is uploaded to the file server, the rest is to store the relevant information in the data table of the attachment management module, so that you can directly use the information in the database when using it, if you want to view images or download files, splice the relevant HTTP address. Let's take a look at the corresponding database records as follows.
With this basic information, we can also transform the HTML editing Control of Winform, which I previously introduced: ZetaHtmlEditControl, (the source code is attached to the Chinese language). After I have made Chinese on all the menu, toolbar, dialog box, and prompt content in English for this control, and added the function of inserting images and printing in the toolbar, the interface is as follows.
By default, the method of adding images must be based on local files. However, after modifying the File Upload mode using FTP, we can get the HTTP address on the control, you can preview and display image files.
The image address constructed in this method belongs to the standard URL address, which can be viewed in various places, as shown in the following interface.
This is the ZetaHtmlEditControl control, which integrates the attachment management module in FTP upload mode to edit online HTML content, it can also be displayed in the HTML editor on the Web interface.
The above is the project component I constructed for the entire WInform development framework, added the FTP upload method, and improved the corresponding scenario requirements. The online HTML editing function is implemented on the ZetaHtmlEditControl control, I hope the development ideas will be helpful to you.