我正在使用MVC项目和jquery html发布数据。尝试将用户选择的文件从第一个表单转移到第二个隐藏表单并使用Jquery.form.js插件(使用.ajaxForm函数)提交第二个表单时,我遇到了一个特定问题。
场景是:
<input type ="file"
控件添加到第二个表单并使用.ajaxForm函数发布第二个表单。但是我的控制器操作没有获取文件流。文件控件附加在第二种形式但不是文件。任何有关这方面的帮助将不胜感激。
以下是我正在使用的代码:
在html中:
<div id="divHiddenUploadForm" class="ui-helper-hidden">
<form id="FrmHiddenToUpload" method="post" enctype="multipart/form-data" action="@Url.Action("Upload","user")">
@Html.HiddenFor(model => model.ContactId)
<input type="submit" id="btnSubmit" value="submit" />
</form>
</div>
<script language="javascript" type="text/javascript"> //using jquery.form plugin
$(document).ready(function () {
var options = {
target: '#frmEditContact', // target element(s) to be updated with server
响应:
type: "POST",
dataType: "xml",
url: "@ViewBag.ImageUrl",
success: function (result) {
alert(result);
}, // post-submit callback
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
},
resetForm: true
};
// bind form using 'ajaxForm'
$('#FrmHiddenToUpload').ajaxForm(options);
答案 0 :(得分:0)
我和我正在做的事情有同样的问题。结果是我写了一个插件,记住上传的文件,如果用户离开而没有提交,则将其删除。欢迎您选择。对不起它的单行间距。
/*
* jQuery FileUpload plugin 1.0
* Author: Mike Santoro
*
* In ordr for the plugin to recreate previews after form submittion the
* hidden form field must be incuded in the form.
* The upload button must directly follow the file field.
* The file field must have the same id and name value.
* To override the settings on a per field bases use the data- scope.
*
maxamount: 1, //maximum number of files to be uploaded
maxsize: 100, //max filesize in kb
timoutFactor: 25, //average speed in kb per second
mimetype: "jpeg,jpg", //file extension to allow
previewtarget: "div.media", //div to add previews to
filepath: "dev\\usa\\webportals", //File upload path. Base path item is evaluated server side valid entries are image and media.
webroot: "http://devimages.mysite.com/images", \\root image path for display
loadimage: "/usa/eng/webPortals/zoomloader.gif", //Image to display while uploading.
deleteimage: "/eng/redRemove.png", //Image to display to remove file.
webpath: "//inquiry/", //web path to accces images for preview
fileloadfield: "#ajaxFileUploadFilesList", //file field to store saved images, for use when rebuilding page
defaulterr: "Your file did not upload. Please try again.", //default error message for failure from server
imagepreviewlist: "jpeg,jpg,png,gif", /list of images to preview
defaultLeaveMessage: "You have uploaded files, if you leave this page your files will be deleted." //message when page is left without sumbmitting the form
*/
;(function($){
$.fn.fileUpload = function(options){
var settings = $.extend({}, $.fn.fileUpload.defaults, options)
, initSelector = this;
loadFiles(settings.fileloadfield);
remFiles(initSelector);
cleanFiles(initSelector);
return initSelector.each(function(index){
var $obj = $(this),
$jForm = $obj.parents("form");
$obj.bind("click.uploadFile", function(event){
var $obj = $(this),
jFile = $obj.prevAll("input[type=file]").attr("id"),
$jFile = $("#" + jFile),
imagesuploaded = $obj.data("imagesuploaded") || 0,
uploadFields = [];
localSettings = $.extend({}, settings, $obj.data());
if($jFile.val().length > 1){
uploadFields.push("<span>");
uploadFields.push("<img style=\"position: absolute;\" src=\"" + localSettings.webroot + localSettings.loadimage + "\" />");
uploadFields.push("<input type=\"hidden\" name=\"ajaxFilePath\" id=\"ajaxFilePath\" value=\"" + localSettings.filepath + "\" />");
uploadFields.push("<input type=\"hidden\" name=\"ajaxMaxSize\" id=\"ajaxMaxSize\" value=\"" + localSettings.maxsize * 1000 + "\" />");
uploadFields.push("<input type=\"hidden\" name=\"ajaxMimeType\" id=\"ajaxMimeType\" value=\"" + localSettings.mimetype + "\" />");
uploadFields.push("<input type=\"hidden\" name=\"ajaxFileName\" id=\"ajaxFileName\" value=\"" + $jFile.val() + "\" />");
uploadFields.push("</span>");
$obj
.hide()
.after(uploadFields.join(""))
.parent()
.find(".error")
.slideUp()
.remove();
togButtons();
$jFile
.attr("name", jFile);
$obj
.data("filelist", ($obj.prev("input[type=hidden]").val() || ""))
.prev("input[type=hidden]")
.remove();
$jForm.bind("submit.upload" + index, function(event){
var strName = ("uploader" + (new Date()).getTime()),
jFrame = $("<iframe name=\"" + strName + "\" id=\"" + strName + "\" src=\"about:blank\" />"),
previewSection = [],
timeout = setTimeout(function(){
errorDisplay($obj, jFrame, "");
jFrame.unbind("load.frameLoad" + index).remove();
console.log("timeout");
}, (localSettings.maxsize || 10000) / localSettings.timoutFactor * 10000);
console.log('timout in : ' + (localSettings.maxsize || 10000) / localSettings.timoutFactor * 10000);
jFrame.css("display", "block");
$("body").append(jFrame);
jFrame.bind("load.frameLoad" + index, function(event){
var objUploadBody = $(window[strName].document),
$jBody = objUploadBody.find("div").is("#json"),
$objData,
showMove = {};
if($jBody){
$jBody = objUploadBody.find("#json");
$objData = $.parseJSON($jBody.html());
if($objData.svrstatus === "0"){
$obj
.data("filelist", ($obj.data("filelist") ? $obj.data("filelist") + "*" : "") + ($objData.filereturn || ""))
.prev("input[type=file]")
.val("")
.end()
.next("span")
.remove();
$jFile
.val("")
.attr("name", jFile + "FileUploadField");
$obj.data("imagesuploaded", imagesuploaded + 1);
if(localSettings.previewtarget.length > 0){
previewSection.push("<div>");
if(localSettings.imagepreviewlist.indexOf($objData.serverfileext.toLowerCase()) > 0){
previewSection.push("<img class=\"removeImg\" data-filename=\"" + $objData.filereturn + "\" src=\"" + localSettings.webroot + localSettings.deleteimage + "\" />");
previewSection.push("<img class=\"filePreview\" src=\"" + localSettings.webroot + localSettings.webpath + $objData.filereturn + "\" title=\"" + $objData.filereturn + " " + $objData.filesize + "\" />");
showMove['width'] = "show";
}
else{
previewSection.push("<img class=\"removeFile\" data-filename=\"" + $objData.filereturn + "\" src=\"" + localSettings.webroot + localSettings.deleteimage + "\" />");
previewSection.push("<div class=\"filePreview\">" + $objData.filereturn + " " + $objData.filesize + "</div>");
showMove['height'] = "show";
}
previewSection.push("</div>");
$obj
.nextAll(localSettings.previewtarget + ":first")
.prepend(previewSection.join(""))
.find("div:first")
.hide()
.animate(showMove);
}
togButtons();
if($obj.data("imagesuploaded") < localSettings.maxamount){
$obj.show();
}
$obj
.before("<input type=\"hidden\" class=\"fileFieldLists\" name=\"" + jFile + "\" value=\"" + ($obj.data("filelist") || "") + "\" />");
$(localSettings.fileloadfield).val($("input[type=hidden].fileFieldLists").serialize());
}
else{
errorDisplay($obj, jFrame, $objData);
}
}
else{
errorDisplay($obj, jFrame, "");
}
clearTimeout(timeout);
jFrame.unbind("load.frameLoad" + index);
setTimeout(function(){jFrame.remove();},100);
});
$jForm
.attr({action: "index.cfm?action=santoro.fileUploadAJAX&_nhd&fileField=" + jFile,
method: "post",
enctype: "multipart/form-data",
encoding: "multipart/form-data",
target: strName});
});
$jForm.trigger("submit.upload" + index);
$jForm.unbind("submit.upload" + index).attr("target", "");
}
else{
$jFile.trigger("click");
}
}); /// end click
});//end each
function togButtons(){
$(initSelector).each(function(){
var $obj = $(this);
$obj.attr("disabled", ($obj.attr("disabled") ? false : true));
});
}
function cleanFiles(obj){
var $obj = $(obj),
$jForm = $obj.parents("form");
$jForm
.find("input[type=button],input[onclick*=Submit],input[value*=Submit],input[value*=Save],input[type=submit]")
.not($obj)
.bind("click.save mouseup.save", function(event){
$(window).unbind('beforeunload.cleanFile unload.removeFiles');
});
$(window).bind('beforeunload.cleanFile', function(event){
var localSettings = $.extend({}, settings),
filesList = "";
$("input[type=hidden].fileFieldLists").each(function(){
var $obj = $(this);
filesList += ($obj.val() || "");
});
$(window).bind('unload.removeFiles', function(event){
var filesList = [];
$("input[type=hidden].fileFieldLists").each(function(){
var $obj = $(this),
localSettings = $.extend({}, settings, $obj.next().data()),
fieldValues = ($obj.val().indexOf("*") ? $obj.val().split("*") : $obj.val()),
fieldValuesCnt = fieldValues.length;
for(var i = 0; i < fieldValuesCnt; i++){
filesList.push(localSettings.filepath + fieldValues[i]);
}
});
if(filesList.length){
deleteFiles(filesList.join(","), false);
}
});
if(filesList.length){
return localSettings.defaultLeaveMessage;
}
});
}
function deleteFiles(fileList, cleaner){
var ajaxOptions = {
url: "index.cfm?action=santoro.fileDeleteAJAX",
type: "GET",
data: {"fileList":fileList},
timeout: 5000,
dataType: "json",
async : cleaner || false,
success: function(data, textStatus, jqXHR) {console.log(data)}
};
$.ajax(ajaxOptions);
}
function errorDisplay($obj, jFrame, $objData){
var localSettings = $.extend({}, settings, $obj.data()),
errText = $objData.errtext || localSettings.defaulterr,
jFile = $obj.prevAll("input[type=file]").attr("id");
$obj
.show()
.before("<input type=\"hidden\" class=\"fileFieldLists\" name=\"" + jFile + "\" value=\"" + ($obj.data("filelist") || "") + "\" />")
.next("span")
.remove()
.end()
.after("<div class=\"error hidden ajaxError\">" + errText + "</div>")
.next(".error")
.removeClass("hidden")
.slideDown("slow");
setTimeout(function(){jFrame.remove()},100);
togButtons();
}
function remFiles(obj){
obj.each(function(){
var $obj = $(this),
localSettings = $.extend({}, settings, $obj.data());
$obj.nextAll(localSettings.previewtarget).first().delegate("img.removeImg, img.removeFile", "click", function(){
var $remObj = $(this),
re = new RegExp("\\*?" + $remObj.data("filename"), "g"),
hideMove = {};
hideMove[($remObj.hasClass("removeImg")? "width" : "height")] = "hide";
$remObj
.parent("div")
.animate(
hideMove
, 200
, function(){
$(this).remove();
}
);
$obj.data("imagesuploaded", $obj.data("imagesuploaded") - 1).show();
$obj
.prevAll("input[type=hidden]:first")
.val(function(){
return $(this).val().replace(re, "");
});
$(localSettings.fileloadfield).val($("input[type=hidden].fileFieldLists").serialize());
deleteFiles(localSettings.filepath + $remObj.data("filename"), true);
});
});
}
function loadFiles(obj){
$(obj).each(function(){
var $obj = $(this),
$loadedFiles = $obj.val().split("&"),
fieldCnt = $loadedFiles.length,
fieldSplit,
fieldValuesCnt = 0,
$ajaxObj,
fieldValues,
isImage = false,
localSettings,
re = new RegExp("\\+", "g"),
previewSection = [];
if($obj.val().length > 1){
for(var i = 0; i < fieldCnt; i++){
fieldSplit = $loadedFiles[i].split("=");
$ajaxObj = $("#" + fieldSplit[0]).next("input[type=button]");
fieldValues = (fieldSplit[0].indexOf("*") ? fieldSplit[1].split("*") : fieldSplit[1]);
fieldValuesCnt = fieldValues.length;
localSettings = $.extend({}, settings, $ajaxObj.data()),
previewSection = [];
$ajaxObj
.data({filelist: fieldSplit[1],
imagesuploaded: fieldValuesCnt
})
.prevAll("input[type=file]:first")
.attr("name", fieldSplit[0] + "FileUploadField")
.end()
.before("<input type=\"hidden\" class=\"fileFieldLists\" name=\"" + fieldSplit[0] + "\" value=\"" + unescape(fieldSplit[1].replace(re, " ")) + "\" />");
if(fieldValuesCnt >= localSettings.maxamount){
$ajaxObj.hide();
}
for(var j = 0; j < fieldValuesCnt; j++){
isImage = fieldValues[j].split(".");
fieldValue = unescape(fieldValues[j].replace(re, " "));
previewSection = [];
if(fieldValue.length > 0){
previewSection.push("<div>");
if(localSettings.imagepreviewlist.indexOf(isImage[1].toLowerCase()) > 0){
previewSection.push("<img class=\"removeImg\" data-filename=\"" + fieldValue + "\" src=\"" + localSettings.webroot + localSettings.deleteimage + "\" />");
previewSection.push("<img class=\"filePreview\" src=\"" + localSettings.webroot + localSettings.webpath + fieldValue + "\" title=\"" + fieldValue + "\" />");
}
else{
previewSection.push("<img class=\"removeFile\" data-filename=\"" + fieldValue + "\" src=\"" + localSettings.webroot + localSettings.deleteimage + "\" />");
previewSection.push("<div class=\"filePreview\">" + fieldValue + "</div>");
}
previewSection.push("</div>");
$ajaxObj
.nextAll(localSettings.previewtarget)
.first()
.prepend(previewSection.join(""));
}
}
}
$(localSettings.fileloadfield).val($("input[type=hidden].fileFieldLists").serialize());
}
});
}
};
$.fn.fileUpload.defaults = {
maxamount: 1,
maxsize: 100,
timoutFactor: 25,
mimetype: "jpeg,jpg",
previewtarget: "div.media",
filepath: "image\\usa\\",
webroot: "http://devimages.mysite.com/usa",
loadimage: "/eng/zoomloader.gif",
deleteimage: "/eng/redRemove.png",
webpath: "/inquiry/",
fileloadfield: "#ajaxFileUploadFilesList",
defaulterr: "Your file did not upload. Please try again.",
imagepreviewlist: "jpeg,jpg,png,gif",
defaultLeaveMessage: "You have uploaded files, if you leave this page your files will be deleted."
};
})(jQuery);