C# ASP.NET 文件上传下载 下载时图片不自动打开

本文介绍了一个用于Web应用的文件上传和下载组件,包括文件格式验证、大小限制及客户端和服务端文件名处理等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.Web.UI.HtmlControls;
using Care365.Model;

namespace Care365.Tools
{
public abstract class FileHelper
{
static Hashtable _allExtension;

public static Hashtable AllExtension
{
get
{
if (_allExtension != null)
{
return _allExtension;
}
else
{

_allExtension = FillExtension();

return _allExtension;
}
}
}
/// <summary>
/// 配置允许用户上传的文件集合
/// </summary>
/// <returns></returns>
private static Hashtable FillExtension()
{
Hashtable table = new Hashtable();
table.Add(".gif", ".gif");
table.Add(".jpg", ".jpg");
table.Add(".jpeg", ".jpeg");
table.Add(".bmp", ".bmp");
table.Add(".png", ".png");

return table;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="relativePath"></param>
/// <returns></returns>
public static List<UploadFile> UploadFile(string relativePath)
{
if (relativePath.LastIndexOf('//') == relativePath.Length)
{
relativePath += "//";
}

//确认目录存在
if (!Directory.Exists(HttpContext.Current.Server.MapPath(relativePath))) Directory.CreateDirectory(HttpContext.Current.Server.MapPath(relativePath));

HttpFileCollection collection = HttpContext.Current.Request.Files;
List<UploadFile> list = new List<UploadFile>();
string fileName;
string clientName;
string servername;
int length = collection.Count;
for (int i = 0; i < length; i++)
{
HttpPostedFile item = collection[i];
fileName = item.FileName;
if (fileName != null && fileName.Trim().Length > 0)
{
string strExtension = fileName.Substring(fileName.LastIndexOf('.'));
//校验上传文件的格式
if (!ExistUploadType(strExtension))
{
UploadFile uf = new UploadFile();
uf.Upload = false;
uf.Remark = "此格式的文件不允许上传!";
list.Add(uf);
continue;
}
//校验文件大小
if (!IsAllowedLength(item.ContentLength))
{
UploadFile uf = new UploadFile();
uf.Upload = false;
uf.Remark = "文件长度过大!";
list.Add(uf);
continue;
}

clientName = fileName.Substring(fileName.LastIndexOf('//') + 1);

servername = string.Format("{0}{1}{2}", relativePath, Code.GetMd5HashCode(Code.GetGUID()), strExtension);

try
{
item.SaveAs(HttpContext.Current.Server.MapPath(servername));
}
catch (Exception e)
{
UploadFile uf = new UploadFile();
uf.Upload = false;
uf.Remark = e.Message;
list.Add(uf);
continue;
}

UploadFile upf = new UploadFile();
upf.Upload = true;
upf.ServerName = servername;
upf.ClientName = clientName;
upf.Remark = "上传成功!";

list.Add(upf);
}
}

return list;
}
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <param name="relativePath">相对路径</param>
/// <returns></returns>
public static UploadFile UploadFile(HttpPostedFile file, string relativePath)
{
if (relativePath.LastIndexOf('//') == relativePath.Length)
{
relativePath += "//";
}

if (!Directory.Exists(relativePath)) Directory.CreateDirectory(relativePath);

string fileName;
string clientName;
string servername;

fileName = file.FileName;
if (fileName != null && fileName.Trim().Length > 0)
{
string strExtension = fileName.Substring(fileName.LastIndexOf('.'));
//校验上传文件的格式
if (!ExistUploadType(strExtension))
{
UploadFile uf = new UploadFile();
uf.Upload = false;
uf.Remark = "此格式的文件不允许上传!";
return uf;
}
//校验文件大小
if (!IsAllowedLength(file.ContentLength))
{
UploadFile uf = new UploadFile();
uf.Upload = false;
uf.Remark = "文件长度过大!";
return uf;
}

clientName = fileName.Substring(fileName.LastIndexOf('//') + 1);

servername = string.Format("{0}{1}{2}", relativePath, Code.GetMd5HashCode(Code.GetGUID()), strExtension);
try
{
file.SaveAs(HttpContext.Current.Server.MapPath(servername));
}
catch (Exception e)
{
UploadFile uf = new UploadFile();
uf.Upload = false;
uf.Remark = e.Message;
return uf;
}

UploadFile upf = new UploadFile();
upf.Upload = true;
upf.ServerName = servername;
upf.ClientName = clientName;
upf.Remark = "上传成功!";

return upf;
}

return null;
}
/// <summary>
/// 文件下载
/// </summary>
/// <param name="Response"></param>
/// <param name="filePath"></param>
public static void DownloadFile(System.Web.HttpResponse Response, string filePath)
{
filePath = filePath.Replace("/", "//");
string fileName = filePath.Substring(filePath.LastIndexOf('//') + 1);

System.IO.FileInfo file = new System.IO.FileInfo(filePath);

if (file.Exists)
{
long dataLengthToRead = file.Length; // 获取下载的文件总大小

Response.AddHeader("Content-Length", dataLengthToRead.ToString());
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName));

switch (file.Extension)
{
case "gif":
Response.ContentType = "image/gif";
break;
case "jpg":
Response.ContentType = "image/jpeg";
break;
case "bmp":
Response.ContentType = "image/bmp";
break;
case "zip":
Response.ContentType = "application/octet-stream";
break;
case "rar":
Response.ContentType = "application/octet-stream";
break;
case "txt":
Response.ContentType = "text/plain";
break;
case "wps":
Response.ContentType = "application/octet-stream";
break;
case "doc":
Response.ContentType = "application/ms-word";
break;
case "xls":
Response.ContentType = "application/ms-excel";
break;
case "swf":
Response.ContentType = "application/x-shockwave-flash";
break;
case "ppt":
Response.ContentType = "application/ms-powerpoint";
break;
case "fla":
Response.ContentType = "application/octet-stream";
break;
case "mp3":
Response.ContentType = "audio/mp3";
break;
}
Response.TransmitFile(filePath);
Response.End();
}
}
/// <summary>
/// 文件下载
/// </summary>
/// <param name="Response">发送对象</param>
/// <param name="filePath">客户端下载文件地址</param>
/// <param name="clientName">指定客户端下载文件名</param>
public static void DownloadFile(System.Web.HttpResponse Response, string filePath, string clientName)
{
filePath = filePath.Replace("/", "//");
string fileName = filePath.Substring(filePath.LastIndexOf('//') + 1);

System.IO.FileInfo file = new System.IO.FileInfo(filePath);

if (file.Exists)
{
long dataLengthToRead = file.Length; // 获取下载的文件总大小
//文件名超过16个字符就会自动截取,防止出现乱码
string temp = clientName.Substring(0, clientName.LastIndexOf('.'));
string ex = clientName.Substring(clientName.LastIndexOf('.'));
if (temp.Length > 16)
{
temp = temp.Substring(0, 16) + ex;
}
else
{
temp = clientName;
}
Response.AddHeader("Content-Length", dataLengthToRead.ToString());
Response.AddHeader("Content-Disposition", "attachment;filename=/"" + System.Web.HttpUtility.UrlEncode(temp, Encoding.UTF8) + "/"");
switch (file.Extension)
{
case "gif":
Response.ContentType = "image/gif";
break;
case "jpg":
Response.ContentType = "image/jpeg";
break;
case "bmp":
Response.ContentType = "image/bmp";
break;
case "zip":
Response.ContentType = "application/octet-stream";
break;
case "rar":
Response.ContentType = "application/octet-stream";
break;
case "txt":
Response.ContentType = "text/plain";
break;
case "wps":
Response.ContentType = "application/octet-stream";
break;
case "doc":
Response.ContentType = "application/ms-word";
break;
case "xls":
Response.ContentType = "application/ms-excel";
break;
case "swf":
Response.ContentType = "application/x-shockwave-flash";
break;
case "ppt":
Response.ContentType = "application/ms-powerpoint";
break;
case "fla":
Response.ContentType = "application/octet-stream";
break;
case "mp3":
Response.ContentType = "audio/mp3";
break;
}
Response.TransmitFile(filePath);
Response.End();
}
}
/// <summary>
/// 校验上传文件是否被允许上传
/// </summary>
/// <param name="extension"></param>
/// <returns></returns>
private static bool ExistUploadType(string extension)
{
if (extension.IndexOf('.') < 0) extension.Insert(0, ".");

return AllExtension.Contains(extension);
}
/// <summary>
/// 如果上传文件的大小超过最大值,返回flase,否则返回true.
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static bool IsAllowedLength(int length)
{
//允许上传文件大小的最大值,可以保存在xml文件中,单位为MB
int i = 4;
//如果上传文件的大小超过最大值,返回flase,否则返回true.
if (length > i * 1048576)
{
return false;
}
return true;
}
/// <summary>
///删除文件,当文件不存在的时候不会产生错误
/// </summary>
/// <param name="path">相对路径</param>
public static void DeleteFile(string path)
{
File.Delete(HttpContext.Current.Server.MapPath(path));
}
}
}

//实体类

using System;
using System.Collections.Generic;
using System.Text;

namespace Care365.Model
{
public class UploadFile
{
string _serverName;

public string ServerName
{
get { return _serverName; }
set { _serverName = value; }
}
string _clientName;

public string ClientName
{
get { return _clientName; }
set { _clientName = value; }
}
bool _upload;

public bool Upload
{
get { return _upload; }
set { _upload = value; }
}

string _remark;

public string Remark
{
get { return _remark; }
set { _remark = value; }
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值