【发布时间】:2015-08-18 05:47:22
【问题描述】:
我正在使用 Jquery Cropit 插件让用户上传和裁剪图像。一旦图像被裁剪到他们喜欢的位置,单击“上传”按钮,它应该将其保存到服务器的指定文件夹中。我可以使用 Cropit 的导出功能将我的 javascript 中的裁剪图像保存到一个变量中。我已将其输出到窗口并验证它正在工作。但是当我进行 ajax 调用以将其发送回我的控制器以保存到服务器时,我不知道如何获取图像。 Request.Files 为空,imageFile 为空。我正在使用 MVC 和 asp.net。
HTML:
<div id="image-cropper">
<div class="cropit-image-preview-container">
<div class="cropit-image-preview"></div>
</div>
<div class="slider-wrapper">
<span class="icon icon-image small-image"></span>
<input class="cropit-image-zoom-input custom" type="range" min="0" max="1" step="0.01">
<span class="icon icon-image large-image"></span>
</div>
<div class="btns">
<!-- The actual file input will be hidden -->
<!-- And clicking on this button will open up select file dialog -->
<input class="cropit-image-input custom" type="file" accept="image/*">
<input type="hidden" class="hidden-image-data" />
<div class="btn select-image-btn">
<span class="icon icon-image"></span>
Select new image
</div>
<div class="btn upload-btn">
<span class="icon icon-box-save"></span>
Upload cropped image
</div>
</div>
</div>
Javascript:
$('#image-cropper').cropit({
imageBackground: true,
onImageLoading: function () {
// these lines are needed to center the background image to match the main cropped image
$(".cropit-image-preview-container").css("width", "500px");
$(".cropit-image-background-container").css("left", "51px");
}
});
// When user clicks select image button,
// open select file dialog programmatically
$('.select-image-btn').click(function () {
$('.cropit-image-input').click();
});
$('.upload-btn').click(function () {
var imageData = $('#image-cropper').cropit('export', {
type: 'image/jpeg'
});
$('.hidden-image-data').val(imageData);
var formData = new FormData();
formData.append("imageFile", imageData);
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
url: '@Url.Action("UploadImage", "Admin")',
//headers: headers,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function (response) {
console.log(response);
},
});
});
控制器动作:
[HttpPost]
//[ValidateAntiForgeryToken]
public bool UploadImage(HttpPostedFileBase imageFile)
{
bool saved = false;
foreach(string file in Request.Files)
{
var fileContent = Request.Files[file];
}
if (imageFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Content/img/products"), imageFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
imageFile.SaveAs(fileSavePath);
if (System.IO.File.Exists(fileSavePath))
{
saved = true;
}
}
return saved;
}
【问题讨论】: