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之 ...
随机推荐
- C++ BASS 实例
#include <iostream> #include <string> #include <map> #include "..\sdk\bass\in ...
- 贪心数列构造——cf1157D
一开始将数列设置为0 1 2 3 4 5 6... 然后从左到右遍历,每位不够就增加即可 #include<bits/stdc++.h> using namespace std; #def ...
- Ubuntu-WPS无法输入中文
WPS无法输入中文 原因:环境变量未正确设置 $ vi /usr/bin/wps,添加以下内容: #!/bin/bash export XMODIFIERS="@im=fcitx" ...
- day 58 Django基础六之ORM中的锁和事务
Django基础六之ORM中的锁和事务 本节目录 一 锁 二 事务 三 xxx 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 锁 行级锁 select_for_update( ...
- 安装MySql社区版(35-3)
1,https://dev.mysql.com/ --------------------------------------------------------------------------- ...
- 豌豆荚Redis集群方案:Codis
Codis简介 Codis是一个分布式Redis解决方案,对于上层的应用来说,连接到CodisProxy和连接原生的RedisServer没有明显的区别(不支持的命令列表),上层应用可以像使用单机的R ...
- AngularJs 报错 Error: [$parse:lexerr]
参考:https://www.cnblogs.com/fangshidaima/p/6048071.html 错误: 根据错误找到报错行: $scope.$apply($scope.param1 = ...
- java_JDK8中新增的时间API
java.time 包含值对象的基础包 java.time.chrono 提供对不同的日历系统的访问 java.time.format 格式化和解析时间的日期 java.time.temporal 包 ...
- AbstractByteBuf 源码分析
主要成员变量 static final ResourceLeakDetector<ByteBuf> leakDetector = new ResourceLeakDetector<B ...
- (转)Windows中杀死占用某个端口的进程
启动tomcat时候,控制台报错,发现是端口占用,于是寻找方法关闭对应的程序. 从网上找了好久,尝试之后,发现不行.开始自己尝试,终于,成功的将占用端口的进程杀掉.在此记录下过程(以8081端口为例) ...