


Detailed explanation of HttpPostedFileBase file upload examples
This article mainly introduces ASP.NET MVC HttpPostedFileBaseFile upload, which has certain reference value. Interested friends can refer to it
This article introduces ASP.NET MVC HttpPostedFileBase file upload, share it with everyone, I hope it will be helpful to everyone
HttpPostedFileBase file upload supports multiple file uploads at one time. If there are pictures, it supports thumbnail saving
File transfer information encapsulation
/// <summary> /// 文件生成方式 /// </summary> public class UpFileMessage { /// <summary> /// 文件名 /// </summary> public string OriginalFileName { get; set; } /// <summary> /// 是否保存略缩图 /// </summary> public bool IsImage { get; set; } /// <summary> /// 文件流 /// </summary> public Stream FileStream { get; set; } /// <summary> /// 生成缩略图的方式 /// [WH]-指定宽高 /// [H]-指定高,按比例缩放宽 /// [W]-指定宽,按比例缩放高 /// </summary> public string Mode { get; set; } /// <summary> /// 略缩图高度 /// </summary> public int? ThumbHeight { get; set; } /// <summary> /// 略缩图宽度 /// </summary> public int? ThumbWidth { get; set; } }
File upload return result
/// <summary> /// 文件上传返回结果 /// </summary> public class UpFileResultMessage { /// <summary> /// 文件保存是否成功 /// </summary> public bool IsSuccess { get; set; } /// <summary> /// 错误消息 /// </summary> public string Message { get; set; } /// <summary> /// 原始文件名-(无扩展名) /// </summary> public string FileName { get; set; } /// <summary> /// 文件名扩展名 /// </summary> public string FileSuffix { get; set; } /// <summary> /// 文件名保存路径 /// </summary> public string FilePath { get; set; } /// <summary> /// 文件类型为图片时 /// 缩略图保存路径 /// </summary> public string ThumbPath { get; set; } /// <summary> /// 保存文件名(无扩展名) /// </summary> public string SaveFileName { get; set; } /// <summary> /// 文件自增ID /// </summary> public int[] FileIdArray { get; set; } }
File upload classLibrary
Requires a reference to System.Webnamespace, and [System.Web.UI.Page] Inherit and call the Server.MapPath method
public class FileUtil : System.Web.UI.Page { /// <summary> /// 图片上传 /// </summary> /// <param name="fileMessage">文件生成方式</param> /// <returns></returns> public UpFileResultMessage UpLoadFile(UpFileMessage fileMessage) { try { string now = DateTime.Today.ToString("yyyyMMdd"); string guid = Guid.NewGuid().ToString(); //获取文件扩展名 var fileSuffix = Path.GetExtension(fileMessage.OriginalFileName); var uploadFolder = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(ParmsConfig.UpFilePathUrl), now); if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } //保存文件名 string saveFileName = guid + fileSuffix; string filePath = Path.Combine(uploadFolder, saveFileName); UpFileResultMessage upFileResult = new UpFileResultMessage() { IsSuccess = true, FileName = Path.GetFileNameWithoutExtension(fileMessage.OriginalFileName), FileSuffix = fileSuffix, FilePath = string.Format(@"{0}/{1}", ParmsConfig.UpFileIPAddressUrl, now), SaveFileName = guid }; using (Stream sourceStream = fileMessage.FileStream) { using (FileStream targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { const int bufferLen = 1024 * 4;//4KB byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0) { targetStream.Write(buffer, 0, count); } } //上传文件为图片时,需创建缩略图 if (fileMessage.IsImage) { var uploadThumbFolder = Path.Combine(uploadFolder, "Thumb"); if (!Directory.Exists(uploadThumbFolder)) { Directory.CreateDirectory(uploadThumbFolder); } using (FileStream targetStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None)) { System.Drawing.Image image = System.Drawing.Image.FromStream(targetStream); int width = image.Width; int height = image.Height; int thumbWidth = 0; int thumbHeight = 0; switch (fileMessage.Mode) { case "WH": //指定高宽缩放(可能变形) thumbWidth = fileMessage.ThumbWidth.HasValue ? fileMessage.ThumbWidth.Value : 200; thumbHeight = fileMessage.ThumbHeight.HasValue ? fileMessage.ThumbHeight.Value : 200; break; case "W": //指定宽,高按比例 thumbWidth = fileMessage.ThumbWidth.HasValue ? fileMessage.ThumbWidth.Value : 200; thumbHeight = height * thumbWidth / width; break; case "H": //指定高,宽按比例 thumbHeight = fileMessage.ThumbHeight.HasValue ? fileMessage.ThumbHeight.Value : 200; thumbWidth = width * thumbHeight / height; break; default: thumbWidth = fileMessage.ThumbWidth.HasValue ? fileMessage.ThumbWidth.Value : 200; thumbHeight = height * thumbWidth / width; break; } string thumbFilePath = Path.Combine(uploadThumbFolder, saveFileName); CreateThumbnail(thumbFilePath, targetStream, thumbWidth, thumbHeight); upFileResult.ThumbPath = string.Format(@"{0}/{1}/Thumb", ParmsConfig.UpFileIPAddressUrl, now); } } } return upFileResult; } catch (Exception ex) { return new UpFileResultMessage() { IsSuccess = false, Message = ex.Message }; } } /// <summary> /// 创建指定图片文件流的缩略图 /// </summary> /// <param name="thumbFilePath">缩略图文件保存路径</param> /// <param name="fileStream">原始文件流</param> /// <param name="width">缩略图宽</param> /// <param name="height">缩略图高</param> private void CreateThumbnail(string thumbFilePath, Stream fileStream, int width, int height) { using (Image image = Image.FromStream(fileStream)) { using (Image thumbnail = image.GetThumbnailImage(width, height, null, IntPtr.Zero)) { thumbnail.Save(thumbFilePath); } } } }
Calling method
var upFileMsg = new UpFileMessage() { IsImage = true, OriginalFileName = platformImg[i].FileName, FileStream = platformImg[i].InputStream, ThumbWidth = ThumbWidth, Mode = "W" }; var upFileResultMsg = new FileUtil().UpLoadFile(upFileMsg);
The above is the detailed content of Detailed explanation of HttpPostedFileBase file upload examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.
