Web API 上传下载文件
1.引用了一个第三方组件 ICSharpCode.SharpZipLib.Zip;
2.具体代码
实体类,可以用hashtable 替代 ,感觉hashtable 比较灵活
public class FileResult
{
public string FileNames { get; set; }
public string Description { get; set; }
public DateTime CreatedTimestamp { get; set; }
public DateTime UpdatedTimestamp { get; set; }
public string FileLength { get; set; }
public string ContentTypes { get; set; }
public string OriginalNames { get; set; }
public string Status { get; set; } public string Msg { get; set; }
}
扩展的修改文件名称
public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public WithExtensionMultipartFormDataStreamProvider(string rootPath)
: base(rootPath)
{ }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
return Guid.NewGuid().ToString() + extension;
} private string GetValidFileName(string filePath)
{
char[] invalids = System.IO.Path.GetInvalidFileNameChars();
return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
}
}
具体上传类
public class UpLoadController : ApiController
{
private const string UploadFolder = "uploads"; [HttpPost]
public Task<IQueryable<FileResult>> UpLoadFile()
{
try
{
string uploadFolderPath = HostingEnvironment.MapPath("~/" + UploadFolder); //如果路径不存在,创建路径
if (!Directory.Exists(uploadFolderPath))
Directory.CreateDirectory(uploadFolderPath);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IQueryable<FileResult>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return new FileResult()
{
FileNames = info.Name,
Description = "描述文本",
ContentTypes = info.Extension.ToString(),
CreatedTimestamp = info.CreationTime,
OriginalNames = info.Name.ToString(),
FileLength = info.Length.ToString()
};
});
return fileInfo.AsQueryable();
}); return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
catch (Exception ex)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
}
} [HttpGet]
public HttpResponseMessage DownloadFile(string fileName)
{
HttpResponseMessage result = null; DirectoryInfo directoryInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/" + UploadFolder));
FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault();
if (foundFileInfo != null)
{
FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open); result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(fs);
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name;
}
else
{
result = new HttpResponseMessage(HttpStatusCode.NotFound);
} return result;
} /// <summary>
/// 压缩文件下载
/// </summary>
/// <param name="fileIds">文件编号</param>
/// <returns></returns>
[HttpGet]
public HttpResponseMessage DownLoad(string fileIds)
{
string customFileName = DateTime.Now.ToString("yyyyMMddHHmmss")+ ".zip";//客户端保存的文件名
string path = HostingEnvironment.MapPath("~/" + UploadFolder + "/" );
HttpResponseMessage response = new HttpResponseMessage();
try
{
string[] filenames = { "4c301d70-a681-46bd-88c1-97a133ee4b79.png", "4648cac5-d15f-45f2-9b06-7a2eebf5c604.jpg" };
using (ZipOutputStream s = new ZipOutputStream(File.Create(path+"/"+ customFileName)))
{
s.SetLevel();
byte[] buffer = new byte[]; foreach (string file in filenames)
{
var entry = new ZipEntry(Path.GetFileName(path+"/"+file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(path + "/" + file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
s.Finish();
s.Close();
}
FileStream fileStream = new FileStream(path + "/" + customFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = customFileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // 这句话要告诉浏览器要下载文件
response.Content.Headers.ContentLength = new FileInfo(path + "/" + customFileName).Length;
}
catch (Exception ex)
{ }
return response;
} /// <summary>
/// 图片上传 [FromBody]string token
/// </summary>
/// <returns></returns>
[HttpPost]
public Task<IQueryable<Hashtable>> ImgUpload()
{
string status = "";
string msg = "";
const int maxSize = ;
const string fileTypes = "gif,jpg,jpeg,png,bmp";
bool isthumb = true;//是否生成缩略图
string PrefixThumbnail = "thumb_"; //随机生成缩略图文件名前缀
string daypath=DateTime.Now.ToString("yyyyMMdd"); // 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); // 文件保存目录路径
string uploadFolderPath = HostingEnvironment.MapPath("~/" + UploadFolder+ "/"+ daypath);
//检查上传的物理路径是否存在,不存在则创建
if (!Directory.Exists(uploadFolderPath))
{
Directory.CreateDirectory(uploadFolderPath);
}
var streamProvider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath);
//var streamProvider = new MultipartFormDataStreamProvider(uploadFolderPath); var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IQueryable<Hashtable>>(t =>
{ if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
} var fileInfo = streamProvider.FileData.Select(i =>
{ var info = new FileInfo(i.LocalFileName); //原始上传名称
LogHelper.writeLog(i.Headers.ContentDisposition.FileName);
string orfilename = GetOrginFileName(i.Headers.ContentDisposition.FileName); if (info.Length <= )
{
status = "";
msg = "请选择上传文件";
}
else if (info.Length > maxSize)
{
status = "";
msg = "上传文件大小超过限制";
}
else
{
var fileExt = info.Extension.ToString();
if (String.IsNullOrEmpty(fileExt) ||
Array.IndexOf(fileTypes.Split(','), fileExt.Substring().ToLower()) == -)
{
status = "";
msg = "不支持上传文件类型";
}
else
{
status = "";
msg = "上传成功";
//生成缩略图
if (isthumb) {
MakeThumbnailImage(uploadFolderPath + "/" + info.Name, uploadFolderPath + "/" + PrefixThumbnail + info.Name, , , "Cut");
}
}
}
Hashtable hs = new Hashtable();
hs["status"] = status;
hs["msg"] = msg;
hs["filename"] = "/"+ UploadFolder + "/"+ daypath +"/"+ info.Name;
hs["orginname"] = orfilename;
return hs;
});
return fileInfo.AsQueryable();
}); return task;
} private string GetOrginFileName(string filePath)
{
string result = "";
try
{
var filename = Regex.Match(filePath, @"[^\\]+$");
result = filename.ToString().Replace("\"", "");
}
catch (Exception)
{ }
return result;
} /// <summary>
/// 生成缩略图
/// </summary>
/// <param name="fileName">源图路径(绝对路径)</param>
/// <param name="newFileName">缩略图路径(绝对路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
private void MakeThumbnailImage(string fileName, string newFileName, int width, int height, string mode)
{
Image originalImage = Image.FromFile(fileName);
int towidth = width;
int toheight = height; int x = ;
int y = ;
int ow = originalImage.Width;
int oh = originalImage.Height; switch (mode)
{
case "HW"://指定高宽缩放(补白)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = ;
y = (originalImage.Height - oh) / ;
}
else
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = ;
x = (originalImage.Width - ow) / ;
}
break;
case "W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = ;
x = (originalImage.Width - ow) / ;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = ;
y = (originalImage.Height - oh) / ;
}
break;
default:
break;
} //新建一个bmp图片
Bitmap b = new Bitmap(towidth, toheight);
try
{
//新建一个画板
Graphics g = Graphics.FromImage(b);
//设置高质量插值法
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.White);
//g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(, , towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
b.Dispose();
}
} /// <summary>
/// 保存图片
/// </summary>
/// <param name="image">Image 对象</param>
/// <param name="savePath">保存路径</param>
/// <param name="ici">指定格式的编解码参数</param>
private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
{
//设置 原图片 对象的 EncoderParameters 对象
EncoderParameters parameters = new EncoderParameters();
parameters.Param[] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)));
image.Save(savePath, ici, parameters);
parameters.Dispose();
}
/// <summary>
/// 获取图像编码解码器的所有相关信息
/// </summary>
/// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
/// <returns>返回图像编码解码器的所有相关信息</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType)
return ici;
}
return null;
} /// <summary>
/// 得到图片格式
/// </summary>
/// <param name="name">文件名称</param>
/// <returns></returns>
public static ImageFormat GetFormat(string name)
{
string ext = name.Substring(name.LastIndexOf(".") + );
switch (ext.ToLower())
{
case "jpg":
case "jpeg":
return ImageFormat.Jpeg;
case "bmp":
return ImageFormat.Bmp;
case "png":
return ImageFormat.Png;
case "gif":
return ImageFormat.Gif;
default:
return ImageFormat.Jpeg;
}
}
}
3.示例代码
<form name="form1" method="post" enctype="multipart/form-data" action="http://localhost:4589/api/UpLoad/ImgUpload">
<input type="file" name="file1" style="width:160px;" />
<input type="file" name="file2" style="width:160px;" />
<input type="submit" name="Submit" value="添加" />
</form>
<img src="" id='testimg'/>
<a href='http://192.168.0.108:8010/api/UpLoad/DownloadFile?fileName=4648cac5-d15f-45f2-9b06-7a2eebf5c604.png'>download</a>
<a href='http://192.168.0.108:8010/api/UpLoad/DownLoad?fileIds=2'>downloadzip</a>
Web API 上传下载文件的更多相关文章
- java web service 上传下载文件
1.新建动态web工程youmeFileServer,新建包com,里面新建类FileProgress package com; import java.io.FileInputStream; imp ...
- 返璞归真 asp.net mvc (11) - asp.net mvc 4.0 新特性之自宿主 Web API, 在 WebForm 中提供 Web API, 通过 Web API 上传文件, .net 4.5 带来的更方便的异步操作
原文:返璞归真 asp.net mvc (11) - asp.net mvc 4.0 新特性之自宿主 Web API, 在 WebForm 中提供 Web API, 通过 Web API 上传文件, ...
- 演示如何通过 web api 上传文件MVC40
演示如何通过 web api 上传文件WebApiWebFormHost/UploadFileController.cs /* * 通过 web api 上传文件 */ using System; u ...
- asp.net 模拟CURL调用微信公共平台API 上传下载多媒体文
近公司项目上在开发微信服务号的接口,需要给用户回复图片或语音或视频,这个时候就需要用到 上传下载多媒体文件接口,微信在这方面推荐采用的是开源函数库curl实现的,CURL项目包括很多版本,我主要测试的 ...
- asp.net 模拟CURL调用微信公共平台API 上传下载多媒体文件接口
FormItem类 public class FormItem { public string Name { get; set; } public ParamType ParamType { get; ...
- SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例
本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...
- C#实现http协议支持上传下载文件的GET、POST请求
C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...
- 【WCF】利用WCF实现上传下载文件服务
引言 前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...
- WebSSH画龙点睛之lrzsz上传下载文件
本篇文章没有太多的源码,主要讲一下实现思路和技术原理 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过lrzsz来完成的,主要是因为其简单方便,不需要额外打开sftp之 ...
随机推荐
- thinkphp cbd模式
ThinkPHP从3.0版本开始引入了全新的CBD(核心Core+行为Behavior+驱动Driver)架构模式,因为从底层开始,框架就采用核心+行为+驱动的架构体系,核心保留了最关键的部分,并在重 ...
- 费用流模板(带权二分图匹配)——hdu1533
/* 带权二分图匹配 用费用流求,增加源点s 和 汇点t */ #include<bits/stdc++.h> using namespace std; #define maxn 1000 ...
- linux安装PyCharm,PyCharm常用快捷键及调试模式,pycharm里面对文件夹或者文件进行重命名
PyCharm常用快捷键及调试模式 2017年10月18日 23:13:43 菜鸟之神 阅读数:5835 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn ...
- JavaWeb三大组件—过滤器filter
JavaWeb三大组件 1. 都需要在web.xml中进行配置ServletListener(2个感知监听器不需要配置)Filter 2. 过滤器 它会在一组资源(jsp.servlet..css.. ...
- JavaScript对象小基础
对象的简单学习: 1.String对象1:属性 在javascript中可以用单引号,或者双引号括起来的一个字符当作 一个字符对象的实例,所以可以在某个字符串后再加上.去调用Strin ...
- POJ 2318 /// 判断点与直线的位置关系
题目大意: n块玩具箱隔板 m个玩具落地点 给定玩具箱的左上和右下两个端点 接下来给定n块隔板的上点的x和下点的x(因为y就是玩具箱的上下边缘) 接下来给定m个玩具落地点 输出n+1个区域各有的玩具数 ...
- Oracle Database 18c数据库安装步骤
1.Oracle官网登录下载https://login.oracle.com/mysso/signon.jsp WINDOWS.X64_180000_db_home.zip 2.D盘根目录新建文件夹: ...
- python Mean Squared Error vs. Structural Similarity Measure两种算法的图片比较
# by movie on 2019/12/18 import matplotlib.pyplot as plt import numpy as np from skimage import meas ...
- LoadRunner内部结构(1)
LoadRunner内部结构(1) 根据http://www.wilsonmar.com/1loadrun.htm 翻译: LoadRunner内部结构 1, 被测系统是由驱动 ...
- 廖雪峰Java11多线程编程-3高级concurrent包-4Concurrent集合
Concurrent 用ReentrantLock+Condition实现Blocking Queue. Blocking Queue:当一个线程调用getTask()时,该方法内部可能让给线程进入等 ...