• ajax+webapi上传图片问题


    自己想写一个原生的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);
                }
            }
    View Code

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

    然后使用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);
            }
        }
    }
    View Code

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

    然后再去页面调试一下,

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

  • 相关阅读:
    DS博客作业03--树
    DS博客作业02--栈和队列
    数据结构——线性表
    结构体
    C博客作业05--指针
    C语言博客作业04--数组
    面向对象设计大作业第二阶段:图书馆系统
    Java程序设计-有理数类的设计
    DS博客作业05-查找
    DS博客作业04-图
  • 原文地址:https://www.cnblogs.com/wjr408/p/6678877.html
Copyright © 2020-2023  润新知