2
因此,我正在处理一个项目并使用进度条上传文件。我有进度条工作。我的文件分段到我的控制器,我需要将它保存到服务器。下面是我对apicontroller如何将文件保存到映射路径apicontroller asp .net mvc4
namespace MvcMovie.Controllers.WebApi
{
public class UploadController : ApiController
{
// Enable both Get and Post so that our jquery call can send data, and get a status
[HttpGet]
[HttpPost]
public HttpResponseMessage Upload()
{
// Get a reference to the file that our jQuery sent. Even with multiple files, they will all be their own request and be the 0 index
HttpPostedFile file = HttpContext.Current.Request.Files[0];
// do something with the file in this space
// {....}
// end of file doing
var filelenght = file.ContentLength;
// Now we need to wire up a response so that the calling script understands what happened
HttpContext.Current.Response.ContentType = "text/plain";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = new { name = file.FileName };
HttpContext.Current.Response.Write(serializer.Serialize(result));
HttpContext.Current.Response.StatusCode = 200;
// For compatibility with IE's "done" event we need to return a result as well as setting the context.response
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
}
代码,但我不能确定如何将文件保存到服务器上,因为它是在段到来。在另外一个项目,我做了我用正常的控制器,只是用这个:
[Authorize]
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
var username = WebSecurity.CurrentUserName;
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/" + username), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
但是当我尝试在我的apicontroller实现使用Server.Mappath代码不起作用。所以我想我的问题有2个部分你如何保存一个上传的文件在apiwebcontroller,以及如何保存它时,它是分段?
这里是我对它的看法的JavaScript,如果你想看看它:
$(function() {
$('#fileupload').fileupload({
dataType: "json",
url: "/api/upload",
limitConcurrentUploads: 1,
sequentialUploads: true,
progressInterval: 100,
maxChunkSize: 10000,
add: function (e, data) {
$('#filelistholder').removeClass('hide');
data.context = $('<div />').text(data.files[0].name).appendTo('#filelistholder');
$('</div><div class="progress"><div class="bar" style="width:0%"></div></div>').appendTo(data.context);
$('#btnUploadAll').click(function() {
data.submit();
});
},
done: function (e, data) {
data.context.text(data.files[0].name + '... Completed');
$('</div><div class="progress"><div class="bar" style="width:100%"></div></div>').appendTo(data.context);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded/data.total * 100, 10);
$('#overallbar').css('width', progress + '%');
},
progress: function (e, data) {
var progress = parseInt(data.loaded/data.total * 100, 10);
data.context.find('.bar').css('width', progress + '%');
}
});
});