我正在使用Jquery Cropit插件让用户上传和裁剪图像。一旦图像被裁剪成他们喜欢的样子,点击“上传”按钮,它就会将其保存到服务器的指定文件夹中。我可以使用Cropit的导出函数将javascript中的裁剪图像保存到一个变量中。我已经将它输出到窗口,并验证它是否正常工作。但是,当我调用ajax将其发送回控制器以保存到服务器时,我不知道如何获取图像。Request.Files为空,并且imageFile为null。我使用的是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;
}发布于 2015-09-18 13:24:01
您正尝试将Base 64数据直接保存到文件中。Cropit "export“函数返回DataURI格式的数据,其中包含以Base64编码的实际二进制数据。
您的代码在您尝试将数据保存到文件时是正确的。在保存之前先使用Base 64解码器对其进行解码。
https://stackoverflow.com/questions/30629889
复制相似问题