自己想写一个原生的JS的图片上传,不想一直只是使用上传文件的框架

网上有很多jquery上传图片上传文件的插件,但是要不是用特定的后台框架接收,要不就是只能上传图片,不是文件,还有一些其他的问题,所以我才想自己玩玩JS原生态的上传文件

文件倒是能保存到服务器上,但是貌似因为返回头文件问题,文件保存成功了,就是JS还是有一条警告,但是不飘红,也请大神指点

先上C#代码吧,用的webapi

[HttpPost]
public async Task<HttpResponseMessage> Post()
{
// Check whether the POST operation is MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
} // Prepare CustomMultipartFormDataStreamProvider in which our multipart form
// data will be loaded.
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/file");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>(); try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await Request.Content.ReadAsMultipartAsync(provider); foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
} // Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
} // We implement MultipartFormDataStreamProvider to override the filename of File which
// will be stored on server, or else the default name will be of the format like Body-
// Part_{GUID}. In the following implementation we simply get the FileName from
// ContentDisposition Header of the Request Body.
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { } public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}

这段代码我也是在网上找的

然后使用postman进行调用接口调试

可以看到,请求完全没问题,返回状态200,并且返回了文件名,

然后看看前台调用,我用的ajax,学习的帖子来源:http://yunzhu.iteye.com/blog/2177923

不过这个帖子后面有个问题,博主一直没回复

先贴html代码,就是一个空的form表单,不给action赋值

<form id="uploadForm">
<p>指定文件名: <input type="text" name="filename" value="" /></p>
<p> 上传文件: <input type="file" name="file" /></ p>
<input type="button" value="上传" id="ajaxUpload" />
</form>

  然后是ajax代码

$("#ajaxUpload").click(function () {
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: 'http://localhost:61221/api/File/Post',
type: 'POST',
data: formData,
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(2);
},
error: function (returndata) {
alert(3);
}
});
})

  

界面如下

点击上传,文件照常保存,没有问题,但是在ajax的回调上,却是进入了error的回调,浏览器打出来的错误是:

可怜小弟英文不好只能找翻译

翻译后为:jquery-3.2.0.js:9557 XMLHttpRequest无法加载http:// localhost:61221 / api / File / Post。 请求资源上不存在“访问控制允许源”标头。 因此,原“http:// localhost:61363”不允许访问。

这个是跨域的问题,详情可以百度一下cors,或者 ,这有个帖子:http://www.jb51.net/article/82384.htm

哈哈,我都是从别人的帖子偷学来的,

现在打开webapi配置路由的地方,我将代码贴上

using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using System.Net.Http.Headers;
using System.Web.Http.Cors; namespace UploadFile
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// 将 Web API 配置为仅使用不记名令牌身份验证。
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// 允许Web API跨域访问
EnableCrossSiteRequests(config);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*"
);
config.EnableCors(cors);
}
}
}

允许Web API跨域访问就差不多了

然后再去页面调试一下,

现在至少页面上不会飘红了,关于这个用户体验的警告,等过两天有时间了再看看吧

ajax+webapi上传图片问题的更多相关文章

  1. Asp.Net WebApi上传图片

    webapi using System; using System.Collections; using System.Collections.Generic; using System.Diagno ...

  2. [Ajax] 使用Ajax异步上传图片文件(非Form表单提交)

    通过表单Form提交来上传文件的方式这里就不说了: 下面介绍,通过js中使用ajax异步上传图片文件: 新建一个html页面和一个一般处理程序即可: 涉及思路: //发送2次Ajax请求完成js异步上 ...

  3. WebApi上传图片 await关键字

    await关键字对于方法执行的影响 将上一篇WebApi上传图片中代码修改(使用了await关键字)如下: [HttpPost] public async Task<string> Pos ...

  4. kindeditor修改图片上传路径-使用webapi上传图片到图片服务器

    kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 在这里我着重介绍一些使用kindeditor修改图片上传路径并通过webapi上传图片到图片服务器的方案. 因为我使用的 ...

  5. kindeditor扩展粘贴图片功能&修改图片上传路径并通过webapi上传图片到图片服务器

    前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...

  6. kindeditor扩展粘贴截图功能&修改图片上传路径并通过webapi上传图片到图片服务器

    前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...

  7. ajax C# webapi上传图片

    html ajax上传图片到服务器 后端采用asp.net webapi 前端有各种现实上传图片的控件,样式可以做的很美观.我这里只用基本的样式做图片上传. 前端代码 <input name=& ...

  8. .Net Core WebApi上传图片的两种方式

    我这边主要是为了上传图片,话不多说,上代码. 方式一:通过Form表单上传 后端: /// <summary> /// 上传图片,通过Form表单提交 /// </summary&g ...

  9. WebClient和HttpClient, 以及webapi上传图片

    httppost请求. applicationkey/x-www-form-urlencoded请求: Email=321a&Name=kkfewwebapi里面, 如果用实体, 能接受到. ...

随机推荐

  1. HDU 6319.Problem A. Ascending Rating-经典滑窗问题求最大值以及COUNT-单调队列 (2018 Multi-University Training Contest 3 1001)

    2018 Multi-University Training Contest 3 6319.Problem A. Ascending Rating 题意就是给你长度为k的数列,如果数列长度k<n ...

  2. POJ 2503.Babelfish-sscanf()函数+strcmp()函数+二分

    Babelfish   Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 44545   Accepted: 18803 Des ...

  3. python——入门系列(一)索引与切片

    1.索引和切片:python当中数组的索引和其他语言一样,从0~n-1,使用索引的方法也是中括号,但是python中的切片的使用简化了代码 索引:取出数组s中第3个元素:x=s[2] 切片:用极少的代 ...

  4. python aiohttp sancio 框架性能测试

    开头先啰嗦两句: 由于本人有开发一个博客的打算,所以近期开始选型python的web框架重头学习,选了两款非常火的 aio web框架 aiohttp 和 sancio 进行性能测试以及开发喜好的调研 ...

  5. 【分解质因数】【树状数组】【快速幂】codeforces 2014 ACM-ICPC Vietnam National Second Round E. ACM

    乘除都在150以内,分解质因数后发现只有35个,建立35个树状数组/线段树,做区间加.区间查询,最后快速幂起来. #include<cstdio> #include<cstring& ...

  6. 【博弈论】【SG函数】poj2311 Cutting Game

    由于异或运算满足结合律,我们把当前状态的SG函数定义为 它所能切割成的所有纸片对的两两异或和之外的最小非负整数. #include<cstdio> #include<set> ...

  7. [CF538H]Summer Dichotomy

    [CF538H]Summer Dichotomy 题目大意: ​ 将若干个学生分为两个班级\(S_1,S_2\),每个班的学生数分别为\(n_1,n_2\)(甚至可以没有学生,也可以没有老师).给出限 ...

  8. Exercise02_09

    import javax.swing.JOptionPane; public class Acceleration { public static void main(String[] args){ ...

  9. Javascript高级程序设计 -- 第三章 -- 总结

    1.Javascript有几种数据类型 2.变量 Javascript有几种数据类型 JavaScript中有5种简单数据类型(也称为基本数据类型):Undefined.Null.Boolean.Nu ...

  10. ylbtech-dbs-m-YinTai(银泰网)

    ylbtech-dbs:ylbtech-dbs-m-YinTai(银泰网) -- =============================================-- DatabaseNam ...