这篇文章主要介绍了webapi2 文件图片上传与下载功能,需要的朋友可以参考下
asp.net framework webapi2 文件上传与下载 前端界面采用ajax的方式执行
一、项目结构
1.app_start配置了跨域访问,以免请求时候因跨域问题不能提交。具体的跨域配置方式如下,了解的朋友请自行略过。
跨域配置:newget安装dll microsofg.aspnet.cors
然后在app_start 文件夹下的webapiconfig.cs中写入跨域配置代码。
public static class webapiconfig
{
public static void register(httpconfiguration config)
{
// web api configuration and services
// web api routes
config.maphttpattributeroutes();
// web api configuration and services
//跨域配置 //need reference from nuget
config.enablecors(new enablecorsattribute("*", "*", "*"));
config.routes.maphttproute(
name: "defaultapi",
routetemplate: "api/{controller}/{id}",
defaults: new { id = routeparameter.optional }
);
//if config the global filter input there need not write the attributes
//config.filters.add(new app.webapi.filters.exceptionattribute_dg());
}
}
跨域就算完成了,请自行测试。
2.新建两个控制器,一个picturescontroller.cs,一个filescontroller.cs当然图片也是文件,这里图片和文件以不同的方式处理的,因为图片的方式文件上传没有成功,所以另寻他路,如果在座的有更好的方式,请不吝赐教!
二、项目代码
1.我们先说图片上传、下载控制器接口,这里其实没什么好说的,就一个get获取文件,参数是文件全名;post上传文件;直接上代码。
using qx_frame.app.webapi;
using qx_frame.filescenter.helper;
using qx_frame.helper_dg;
using qx_frame.helper_dg.extends;
using system;
using system.collections.generic;
using system.diagnostics;
using system.io;
using system.linq;
using system.net;
using system.net.http;
using system.net.http.headers;
using system.text;
using system.threading.tasks;
using system.web.http;
/**
* author:qixiao
* create:2017-5-26 16:54:46
* */
namespace qx_frame.filescenter.controllers
{
public class picturescontroller : webapicontrollerbase
{
//get : api/pictures
public httpresponsemessage get(string filename)
{
httpresponsemessage result = null;
directoryinfo directoryinfo = new directoryinfo(io_helper_dg.rootpath_mvc + @"files/pictures");
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;
}
//post : api/pictures
public async task<ihttpactionresult> post()
{
if (!request.content.ismimemultipartcontent())
{
throw new exception_dg("unsupported media type", 2005);
}
string root = io_helper_dg.rootpath_mvc;
io_helper_dg.createdirectoryifnotexist(root + "/temp");
var provider = new multipartformdatastreamprovider(root + "/temp");
// read the form data.
await request.content.readasmultipartasync(provider);
list<string> filenamelist = new list<string>();
stringbuilder sb = new stringbuilder();
long filetotalsize = 0;
int fileindex = 1;
// this illustrates how to get the file names.
foreach (multipartfiledata file in provider.filedata)
{
//new folder
string newroot = root + @"files/pictures";
io_helper_dg.createdirectoryifnotexist(newroot);
if (file.exists(file.localfilename))
{
//new filename
string filename = file.headers.contentdisposition.filename.substring(1, file.headers.contentdisposition.filename.length - 2);
string newfilename = guid.newguid() + "." + filename.split('.')[1];
string newfullfilename = newroot + "/" + newfilename;
filenamelist.add($"files/pictures/{newfilename}");
fileinfo fileinfo = new fileinfo(file.localfilename);
filetotalsize += fileinfo.length;
sb.append($" #{fileindex} uploaded file: {newfilename} ({ fileinfo.length} bytes)");
fileindex++;
file.move(file.localfilename, newfullfilename);
trace.writeline("1 file copied , filepath=" + newfullfilename);
}
}
return json(return_helper.success_msg_data_dcount_httpcode($"{filenamelist.count} file(s) /{filetotalsize} bytes uploaded successfully! details -> {sb.tostring()}", filenamelist, filenamelist.count));
}
}
}
里面可能有部分代码在helper帮助类里面写的,其实也仅仅是获取服务器根路径和如果判断文件夹不存在则创建目录,这两个代码的实现如下:
public static string rootpath_mvc
{
get { return system.web.httpcontext.current.server.mappath("~"); }
}
//create directory
public static bool createdirectoryifnotexist(string filepath)
{
if (!directory.exists(filepath))
{
directory.createdirectory(filepath);
}
return true;
}
2.文件上传下载接口和图片大同小异。
using qx_frame.app.webapi;
using qx_frame.filescenter.helper;
using qx_frame.helper_dg;
using system.collections.generic;
using system.diagnostics;
using system.io;
using system.linq;
using system.net;
using system.net.http;
using system.net.http.headers;
using system.text;
using system.threading.tasks;
using system.web;
using system.web.http;
/**
* author:qixiao
* create:2017-5-26 16:54:46
* */
namespace qx_frame.filescenter.controllers
{
public class filescontroller : webapicontrollerbase
{
//get : api/files
public httpresponsemessage get(string filename)
{
httpresponsemessage result = null;
directoryinfo directoryinfo = new directoryinfo(io_helper_dg.rootpath_mvc + @"files/files");
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;
}
//post : api/files
public async task<ihttpactionresult> post()
{
//get server root physical path
string root = io_helper_dg.rootpath_mvc;
//new folder
string newroot = root + @"files/files/";
//check path is exist if not create it
io_helper_dg.createdirectoryifnotexist(newroot);
list<string> filenamelist = new list<string>();
stringbuilder sb = new stringbuilder();
long filetotalsize = 0;
int fileindex = 1;
//get files from request
httpfilecollection files = httpcontext.current.request.files;
await task.run(() =>
{
foreach (var f in files.allkeys)
{
httppostedfile file = files[f];
if (!string.isnullorempty(file.filename))
{
string filelocalfullname = newroot + file.filename;
file.saveas(filelocalfullname);
filenamelist.add($"files/files/{file.filename}");
fileinfo fileinfo = new fileinfo(filelocalfullname);
filetotalsize += fileinfo.length;
sb.append($" #{fileindex} uploaded file: {file.filename} ({ fileinfo.length} bytes)");
fileindex++;
trace.writeline("1 file copied , filepath=" + filelocalfullname);
}
}
});
return json(return_helper.success_msg_data_dcount_httpcode($"{filenamelist.count} file(s) /{filetotalsize} bytes uploaded successfully! details -> {sb.tostring()}", filenamelist, filenamelist.count));
}
}
}
实现了上述两个控制器代码以后,我们需要前端代码来调试对接,代码如下所示。
<!doctype>
<head>
<script src="jquery-3.2.0.min.js"></script>
<!--<script src="jquery-1.11.1.js"></script>-->
<!--<script src="ajaxfileupload.js"></script>-->
<script>
$(document).ready(function () {
var appdomain = "http://localhost:3997/";
$("#btn_fileupload").click(function () {
/**
* 用ajax方式上传文件 -----------
* */
//-------asp.net webapi fileupload
//
var formdata = new formdata($("#uploadform")[0]);
$.ajax({
url: appdomain + 'api/files',
type: 'post',
data: formdata,
async: false,
cache: false,
contenttype: false,
processdata: false,
success: function (data) {
console.log(json.stringify(data));
},
error: function (data) {
console.log(json.stringify(data));
}
});
//----end asp.net webapi fileupload
//----.net core webapi fileupload
// var fileupload = $("#files").get(0);
// var files = fileupload.files;
// var data = new formdata();
// for (var i = 0; i < files.length; i++) {
// data.append(files[i].name, files[i]);
// }
// $.ajax({
// type: "post",
// url: appdomain+'api/files',
// contenttype: false,
// processdata: false,
// data: data,
// success: function (data) {
// console.log(json.stringify(data));
// },
// error: function () {
// console.log(json.stringify(data));
// }
// });
//--------end net core webapi fileupload
/**
* ajaxfileupload.js 方式上传文件
* */
// $.ajaxfileupload({
// type: 'post',
// url: appdomain + 'api/files',
// secureuri: false,
// fileelementid: 'files',
// success: function (data) {
// console.log(json.stringify(data));
// },
// error: function () {
// console.log(json.stringify(data));
// }
// });
});
//end click
})
</script>
</head>
<title></title>
<body>
<article>
<header>
<h2>article-form</h2>
</header>
<p>
<form action="/" method="post" id="uploadform" enctype="multipart/form-data">
<input type="file" id="files" name="files" placeholder="file" multiple>file-multiple属性可以选择多项<br><br>
<input type="button" id="btn_fileupload" value="fileupload">
</form>
</p>
</article>
</body>
至此,我们的功能已全部实现,下面我们来测试一下:
可见,文件上传成功,按预期格式返回!
下面我们测试单图片上传->
然后我们按返回的地址进行访问图片地址。
发现并无任何压力!
下面测试多图片上传->
完美~
至此,我们已经实现了webapi2文件和图片上传,下载的全部功能。
这里需要注意一下web.config的配置上传文件支持的总大小,我这里配置的是最大支持的文件大小为1mb
<requestfiltering>
<requestlimits maxallowedcontentlength="1048576" />
</requestfiltering>
<system.webserver>
<handlers>
<remove name="extensionlessurlhandler-integrated-4.0" />
<remove name="optionsverbhandler" />
<remove name="traceverbhandler" />
<add name="extensionlessurlhandler-integrated-4.0" path="*." verb="*" type="system.web.handlers.transferrequesthandler" precondition="integratedmode,runtimeversionv4.0" />
</handlers>
<security>
<requestfiltering>
<requestlimits maxallowedcontentlength="1048576" /><!--1mb-->
</requestfiltering>
</security>
</system.webserver>
【相关推荐】
1. asp.net免费视频教程
2. 详细介绍asp.net mvc--路由
3. 详细介绍asp.net mvc--控制器(controller)
4. 详细介绍asp.net mvc--视图
以上就是分享webapi2 文件图片上传与下载功能实例的详细内容。
