文件上传Jquery WebApi [英] File upload Jquery WebApi
本文介绍了文件上传Jquery WebApi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码将文件上传到服务器,但文件未上传.
HTML:
<button type="submit">上传</button></表单>
Javascript:
//钩入表单的提交事件.$('#upload').submit(function () {//为了在这个例子中保持简单,我们将//使用 FormData XMLHttpRequest Level 2 对象(它//需要现代浏览器,例如IE10+、Firefox 4+、Chrome 7+、Opera 12+ 等).var formData = new FormData();//我们将获取我们的文件上传表单元素(只有一个,因此是 [0]).var opmlFile = $('#opmlFile')[0];//如果这个例子我们只抓取一个文件(并希望至少有一个).formData.append("opmlFile", opmlFile.files[0]);//现在我们可以发送我们的上传了!$.ajax({url: 'api/upload',//我们将发送到我们的 Web API UploadControllerdata: formData,//传递我们花哨的表单数据//防止 jQuery 试图用我们的帖子做聪明的事情//将中断我们的上传,我们将以下设置为 false缓存:假,内容类型:假,过程数据:假,//我们正在做一个帖子,很明显.类型:'POST',成功:函数(){//成功!警报('哇!');}});//返回 false 将阻止事件//冒泡并重新发布表单(同步).返回假;});
控制器如下:
使用系统;使用 System.IO;使用 System.Net;使用 System.Net.Http;使用 System.Web;使用 System.Web.Http;类 UploadController : ApiController{公共异步无效 Post(){如果 (!Request.Content.IsMimeMultipartContent()){throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "此请求格式不正确"));}//我们将上传的文件存储在 Web 应用程序的 App_Data 特殊文件夹下的 Uploads 文件夹中var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Uploads/"));//一旦文件被写出,我们就可以处理它们.await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>{如果(t.IsFaulted || t.IsCanceled){抛出新的 HttpResponseException(HttpStatusCode.InternalServerError);}//在这里我们可以遍历每个上传的文件.foreach(t.Result.FileData 中的 var fileData){//一些好的做法是在我们进行处理之前检查 MIME 类型,例如对于 XML:if (fileData.Headers.ContentType.MediaType.Equals("text/xml", StringComparison.InvariantCultureIgnoreCase)){//这就是我们读取内容的方式(注意,您可能希望异步执行此操作//但让我们暂时保持简单).字符串内容 = File.ReadAllText(fileData.LocalFileName);}}});}}
操作命中,但文件未上传.
解决方案
你可以尝试用普通按钮代替提交按钮 -
控制器动作 -
public HttpResponseMessage Post(){HttpResponseMessage 结果 = null;var httpRequest = HttpContext.Current.Request;//检查文件是否可用如果(httpRequest.Files.Count > 0){var files = new List();//交互文件并保存在服务器上foreach(httpRequest.Files 中的字符串文件){varpostedFile = httpRequest.Files[file];var filePath = HttpContext.Current.Server.MapPath("~/" + PostedFile.FileName);postFile.SaveAs(filePath);文件.添加(文件路径);}//返回结果结果 = Request.CreateResponse(HttpStatusCode.Created, files);}别的{//返回 BadRequest(没有可用的文件)结果 = Request.CreateResponse(HttpStatusCode.BadRequest);}返回结果;}
输出 -
I used this following code to upload file to server, but the file is not uploaded.
Html:
<form id="upload">
<div>
<label for="myFile"></label>
<div>
<input type="file" id="myFile" />
</div>
</div>
<button type="submit">Upload</button>
</form>
Javascript:
// Hook into the form's submit event.
$('#upload').submit(function () {
// To keep things simple in this example, we'll
// use the FormData XMLHttpRequest Level 2 object (which
// requires modern browsers e.g. IE10+, Firefox 4+, Chrome 7+, Opera 12+ etc).
var formData = new FormData();
// We'll grab our file upload form element (there's only one, hence [0]).
var opmlFile = $('#opmlFile')[0];
// If this example we'll just grab the one file (and hope there's at least one).
formData.append("opmlFile", opmlFile.files[0]);
// Now we can send our upload!
$.ajax({
url: 'api/upload', // We'll send to our Web API UploadController
data: formData, // Pass through our fancy form data
// To prevent jQuery from trying to do clever things with our post which
// will break our upload, we'll set the following to false
cache: false,
contentType: false,
processData: false,
// We're doing a post, obviously.
type: 'POST',
success: function () {
// Success!
alert('Woot!');
}
});
// Returning false will prevent the event from
// bubbling and re-posting the form (synchronously).
return false;
});
The Controller is as follows:
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
class UploadController : ApiController
{
public async void Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
// We'll store the uploaded files in an Uploads folder under the web app's App_Data special folder
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Uploads/"));
// Once the files have been written out, we can then process them.
await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
// Here we can iterate over each file that got uploaded.
foreach (var fileData in t.Result.FileData)
{
// Some good things to do are to check the MIME type before we do the processing, e.g. for XML:
if (fileData.Headers.ContentType.MediaType.Equals("text/xml", StringComparison.InvariantCultureIgnoreCase))
{
// And this is how we can read the contents (note you would probably want to do this asychronously
// but let's try keep things simple for now).
string contents = File.ReadAllText(fileData.LocalFileName);
}
}
});
}
}
The action hit, but the file is not uploaded.
解决方案
Instead of submit button can you try with normal button -
<form enctype="multipart/form-data">
<label>
Using JQuery
</label>
<input name="file" type="file" id="me" />
<input type="button" id="Upload" value="Upload" />
</form>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#Upload').click(function () {
var formData = new FormData();
var opmlFile = $('#me')[0];
formData.append("opmlFile", opmlFile.files[0]);
$.ajax({
url: 'http://localhost:23133/api/file',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
</script>
Controller Action -
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();
// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
files.Add(filePath);
}
// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
Output -
这篇关于文件上传Jquery WebApi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文