Home > Backend Development > C#.Net Tutorial > How to add support for FTP upload and preview in the attachment management module?

How to add support for FTP upload and preview in the attachment management module?

零下一度
Release: 2017-06-23 16:20:57
Original
2138 people have browsed it

In the previously introduced attachment management modules, "Winform Development Framework's Universal Attachment Management Module" and "Winform Development Framework's Attachment Management Application" introduce the management functions of attachments. Through the processing of database records and file management, It realizes the integrated management of attachment files and records, and can be used in the stand-alone version of the WInform framework or in the distributed hybrid development framework. As some development scenarios become richer, we need to upload files via FTP, so for This attachment management module is expanded to suit more practical project needs.

1. Implementation ideas for FTP upload and HTTP file preview

The bottom layer of attachment management we envision needs to be reused in Winform, Web and other development projects, so the bottom layer design needs to be considered Corresponding processing can be integrated later using WInform's HTML editing control or Web's HTML editing control. Attachments are unified and implemented in one component.

With the help of FTP file upload, our stand-alone version or the LAN-based Winform interface program can also build a separate FTP server to achieve file sharing; in the distributed hybrid development framework, for file upload , you can choose service-based file system writing, and you can also upload based on FTP.

Upload files based on the FTP method of the hybrid framework. The logical relationship is as follows.

After the file is uploaded to the file system through FTP, we build an HTTP service in the file system, so that the corresponding HTTP address can be used to download the file, and View images and other operations (can be implemented in the HTML editor).

2. Introducing FTP components to implement file upload

Using FTP to upload, although there is an FTPHelper class available in your own public class library, but relatively speaking, I We are more willing to introduce more complete and powerful FTP open source components for related processing. Here we use the FluentFTP component (GitHub address: ), which is a widely used and powerful FTP component.

FluentFTP is an FTP class library based on .Net developed by foreigners that supports FTP and FTPS. FluentFTP is a fully managed FTP client that is designed to be easy to use and easy to expand. It supports file and directory listing, uploading and downloading files and SSL/TLS connections. It can connect to Unix and Windows IIS to establish FTP servers. This project is developed entirely in managed C#.

The usage code of this component is pasted here so that you can have an intuitive understanding of it.

// 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 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();
Copy after login

With this understanding, in ordinary Winform programs or hybrid framework programs, we can load this information in the code by configuring the specified FTP related information. Perform FTP login, file upload, download and other operations.

3. Implementation of Attachment Management Module

With the above ideas and the assistance of components, we can implement FTP by performing relevant upgrades on the original attachment management module. Upload mode is handled.

First of all, for convenience, we first define a configuration entity class to obtain FTP server, user name, password and other parameters, as shown below.

    /// <summary>/// FTP配置信息/// </summary>    [DataContract]
    [Serializable]public class FTPInfo
    {/// <summary>/// 默认构造函数/// </summary>public FTPInfo()
        {

        }/// <summary>/// 参数化构造函数/// </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服务地址/// </summary>        [DataMember]public string Server { get; set; }/// <summary>/// FTP用户名/// </summary>        [DataMember]public string User { get; set; }/// <summary>/// FTP密码/// </summary>        [DataMember]public string Password { get; set; }/// <summary>/// FTP的基础路径,如可以指定为IIS的路径::8000 ,方便下载打开/// </summary>        [DataMember]public string BaseUrl { get; set; }
    }
Copy after login

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

        /// <summary>/// 获取配置的FTP配置参数/// </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);
        }
Copy after login

Our configuration file is as follows.

The component code using FluentFTP is as follows.

//使用FluentFTP操作FTP文件FtpClient client = new FtpClient(ftpInfo.Server, ftpInfo.User, ftpInfo.Password);
Copy after login

Then call the FTP component to determine the directory, if not, just create one.

//确定日期时间目录(格式:yyyy-MM),不存在则创建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);
}
Copy after login

Finally, use the component to upload the file. Upload the file here. Since the byte array is stored in the previous FileUploadInfo entity class, you can also use the FTP component to directly upload the byte array. .

//使用FTP上传文件//避免文件重复,使用GUID命名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);
Copy after login

After the file is uploaded to the file server, all that is left is to store the relevant information in the data table of the attachment management module. In this way, the information in the database can be directly used when using it. If you need to view pictures or Download the file and then splice the relevant HTTP addresses. Let’s take a look at the corresponding database record screenshot as shown below.

With this basic information, we can also transform the Winform HTML editing control I introduced before: ZetaHtmlEditControl (share an HTML editing control Zeta HTML Edit in Winform Control (Chinese version with source code), I translated all the English menus, toolbars, dialog boxes, prompt content and other resources of this control into Chinese, and added the functions of inserting pictures and printing in the toolbar, and the interface is as follows.

By default, the way we add pictures is definitely based on local files; but after we modified it to use FTP to upload files, we got HTTP on the control Address, you can preview and display the image file.

The image address constructed by this method is a standard URL address and can be viewed in various places, as shown in the following interface.

This is the ZetaHtmlEditControl control. It integrates the attachment management module that we have completed in the FTP upload mode earlier to realize the function of editing online HTML. Such HTML content can also be suitable for It is displayed in the HTML editor under the web interface.

The above are the project components I constructed for the entire WInform development framework. I added the FTP upload method and improved the corresponding scene requirements. I implemented the function of editing online HTML on the ZetaHtmlEditControl control. I hope the development ideas will be useful to you. Some gain.

The above is the detailed content of How to add support for FTP upload and preview in the attachment management module?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template