AJAX显示图片后上传
AJAX Show Image after Upload
我正在使用ajax上传文件近3个小时,并成功地使其工作,请检查代码:
视图<div class="form-horizontal">
<div class="form-group">
@Html.Label("Choose Image(s)", new { @class = "control-label col-sm-3" })
<div class="col-sm-5">
<input type="file" name="UploadFile" id="UploadFile" accept=".png, .jpg, .gif" multiple />
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-3">
<input type="button" value="Save" id="save" class="add btn btn-primary" />
<div style="color:red">
@ViewBag.error
</div>
</div>
</div>
</div>
<div style="margin-top: 17px;">
@foreach (var item in Model.Content)
{
<div class="gallery">
<a href="@item.ImagePath" title="@item.Description" data-gallery>
<img src="@item.ThumbPath" alt="@item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete btn btn-danger" value="Delete" data-picid="@item.PhotoId" />
</div>
}
</div>
控制器[HttpPost]
public ActionResult Create(Photo photo)
{
var model = new Photo();
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
model.Description = photo.Description;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.ThumbPath = String.Format(@"/GalleryImages/thumbs/{0}{1}", fileName, extension);
model.ImagePath = String.Format(@"/GalleryImages/{0}{1}", fileName, extension);
// Save thumbnail size image, 100 x 100
SaveToFolder(img, fileName, extension, new Size(200, 200), model.ThumbPath);
// Save large size image, 800 x 800
SaveToFolder(img, fileName, extension, new Size(600, 600), model.ImagePath);
}
// Save record to database
model.CreatedOn = DateTime.Now;
db.Photos.Add(model);
db.SaveChanges();
}
return Json("File Uploaded Successfully");
}
JQuery/AJAX <script type="text/javascript">
$('#UploadFile').on('change', function (e) {
var $this = $(this);
var files = e.target.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]);
}
$.ajax({
type: "POST",
url: '/Home/Create',
contentType: false,
processData: false,
data: data,
success: function (result) {
console.log(result);
//add code to refresh the gallery with the new uploaded image
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("Error! This browser does not support file upload, please change your browser");
}
}
});
</script>
SavetoFolder
private void SaveToFolder(Image img, string fileName, string extension, Size newSize, string pathToSave)
{
// Get new image resolution
Size imgSize = NewImageSize(img.Size, newSize);
using (System.Drawing.Image newImg = new Bitmap(img, imgSize.Width, imgSize.Height))
{
newImg.Save(Server.MapPath(pathToSave), img.RawFormat);
}
}
NewImageSize
public Size NewImageSize(Size imageSize, Size newSize)
{
Size finalSize;
double tempval;
if (imageSize.Height > newSize.Height || imageSize.Width > newSize.Width)
{
if (imageSize.Height > imageSize.Width)
tempval = newSize.Height / (imageSize.Height * 1.0);
else
tempval = newSize.Width / (imageSize.Width * 1.0);
finalSize = new Size((int)(tempval * imageSize.Width), (int)(tempval * imageSize.Height));
}
else
finalSize = imageSize; // image is already small size
return finalSize;
}
,但问题是我必须刷新浏览器看到添加的图像,我应该把什么在ajax成功上传添加图像动态不刷新浏览器?
既然您可以选择上传多个图像,我建议使用以下方法:
你的控制器现在看起来像:
[HttpPost]
public ActionResult Create(Photo photo)
{
List<Photo> model = new List<Photo>();
//create list of photo model
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
string thumpath,imagepath = "";
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.Add(new Photo(){
Description=photo.Description,
ThumbPath = String.Format(@"/GalleryImages/thumbs/{0}{1}", fileName, extension),
ImagePath = String.Format(@"/GalleryImages/{0}{1}", fileName, extension),
CreatedOn=DateTime.Now
});
//fill each detail of model here
thumpath = String.Format(@"/GalleryImages/thumbs/{0}{1}", fileName, extension);
//separate variables to send it to SaveToFolder Method
imagepath = String.Format(@"/GalleryImages/{0}{1}", fileName, extension);
SaveToFolder(img, fileName, extension, new Size(200, 200), thumpath);
SaveToFolder(img, fileName, extension, new Size(600, 600), imagepath);
}
}
foreach(var md in model)
{
//loop again for each content in model
db.Photos.Add(md);
db.SaveChanges();
}
return Json(new {model=model },JsonRequestBehavior.AllowGet);
//return the model here
}
在ajax success
中,您可以使用模型返回值创建图像,如下所示:
success: function (result) {
var model = result.model;
$(model).each(function (key,value) {
$('<img />').attr({
src: value.ThumbPath
}).appendTo("body");
//note you can append it to anywhere, like inside container or something
})
}
我将在成功函数中使用jQuery设置img标签的src属性:
success: function (result) {
$("img").attr('src' , '/path/to/your/img');
},
如果你不知道客户端图像的公共路径,你可以使用响应对象:
return Json("{ path : "+model.ImagePath+"."+fileName+"."+extension+"}");
有几种可能性,使用哪种取决于图片大小等。我个人(如果图像不是太大)将在服务器端转换图像到base64,并返回它与ajax和显示从服务器返回的数据,当然它也需要转换。
看看这篇文章,我想它会帮到你的:)
Base64编码图像
相关文章:
- 无法在通过jQuery的ajax加载的页面中执行javascript
- 如何通过ajax刷新JSF填充的javascript变量
- 如何在php文件中获取$.post-ajax传递的值
- Replacing $ .ajax?
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- Ajax发布表单序列化,发布引号'
- 通过Ajax将JavaScript函数传递给PHP文件
- ajax请求的顺序总是不同的
- 可以't使用Polymer's的核心ajax
- Ajax Live搜索发布到Laravel视图
- Ajax聊天消息重复而不仅仅是更新
- 从控制器返回后Ajax启动事件激发
- PHP AJAX图片上传示例不上传
- 从ajax请求中获取javascript对象
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 如何在Javascript中解析AJAX数组的特定部分
- Ajax文件加载和<输入>文件加载
- Javascript/jQuery中的并行Ajax调用
- Ajax-如何获取数据
- JS验证ajax返回的html中的表单数据