AJAX显示图像上传

问题描述:

后,我工作的上传使用AJAX几乎3小时文件,并成功地设法使它工作,请检查代码:AJAX显示图像上传

查看

<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; 
} 

,但问题是我必须刷新浏览器中看到添加的形象,我应该放什么在阿贾克斯sucess上传添加图像动态无刷新浏览器吗?

+0

随着Json的'success'消息返回图像的**拇指路径/图片路径**并使它对'DOM'在'success'或返回'模型'本身..如果可能的话分享你的'SaveToFolder'代码 –

+0

添加savetofolder代码 – Nevi

+0

另外'NewImageSize'方法.. :) –

既然你有选择上传多张图片我建议去与下面的方法:

控制器现在看起来像:

[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 
    }) 
} 
+0

你好大师我们可以说在聊天我需要帮助的东西 – Nevi

+0

是的请..创建一个,并邀请我.. –

+0

不能创建一个房间 – Nevi

我将设置img标签usign的jQuery的src属性在你的成功的功能:

success: function (result) { 
     $("img").attr('src' , '/path/to/your/img'); 
    }, 

如果你不知道你上,你可以使用响应对象客户端图像的公共路径:

return Json("{ path : "+model.ImagePath+"."+fileName+"."+extension+"}"); 
+0

我会试试这个看看如果它有效。 – Nevi

有几种可能性,其中使用取决于图像大小等 本人来说我(如果图像是不是太大)将在服务器端转换图片OT Base64和使用Ajax返回并显示数据从服务器返回的cours它也需要转换。

看看这篇文章,我想我会帮你:)

Base64 encoded image

+0

对,在我的控制器中将图像转换为base64,那么在Ajax中如何工作? – Nevi

+0

您只需从控制器的base64编码值返回并插入到您的HTML中,如'div。html('')' – Tomaszeek