自己想寫一個原生的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跨域訪問就差不多了
然后再去頁面調試一下,
現在至少頁面上不會飄紅了,關於這個用戶體驗的警告,等過兩天有時間了再看看吧