我目前有一些工作代码可以将文档上传到App_data文件,但是我需要能够区分上传的文件,如果它们具有相同的名称。我想通过修改文件名来做到这一点:ID" "文件名
我曾尝试将其包含在传递给控制器的对象中,但我无法将其存储在任何地方(我认为它在传递时会被剥离?)。
这是我目前的代码:
var files = $('#txtUploadFile')[0].files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
// data.uploadName = task.Id + " " + files[0].name;
// File.filename = Id + " " + file.filename;
$.ajax({
type: "POST",
url: '../Document/UploadFiles/',
contentType: false,
processData: false,
//data: {'id': (nextRef + 1), 'fileLocation': files[0].name }, // THIS DOESN'T WORK
data: data, // THIS WORKS WITHOUT ANY OTHER VARIABLES
dataType: "json",
success: function (result) {
//alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
alert(log(err));
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
[HttpPost]
public JsonResult UploadFiles()//string id, string fileLocation)
{
try
{
foreach (string file in Request.Files)
{
var hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = Path.GetFileName(file);
var path = Path.Combine(Server.MapPath("~/App_Data/"), Path.GetFileName(hpf.FileName));
// Save the file
hpf.SaveAs(path);
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return this.Json("Upload failed");
}
return this.Json("File uploaded successfully");
}
答案 0 :(得分:0)
your html should be
<div><input type="file" name="UploadFile" id="fileupload" Class="fileupload" />
</div>
your ajax call should be
$.ajax({
type: "POST",
url: '/MyController/UploadFiles?id=' + myID,
contentType: false,
processData: false,
data: data,
success: function(result) {
console.log(result);
},
error: function (xhr, status, p3, p4){
});
//and your controller
[HttpPost]
public JsonResult UploadFiles(string id)
{
// whatever you want to that id
}
Happy coding...
答案 1 :(得分:0)
change from url: '../Document/UploadFiles/',
to url: '@Url.Action("UploadFiles","YourController")
and in your controller
public class YourController:Controller{
[HttpPost]
publiction ActionResult UploadFiles(){
if (Request.Files != null && Request.Files.Count > 0)
{
string path=Server.MapPath("~/App_Data");
Request.Files[0].SaveAs(path + fileName);
return Json("File uploaded","text/json",JsonRequestBehavior.AllowGet);
}
return Json("No File","text/json",JsonRequestBehavior.AllowGet);
}
}