Javascript 上传后显示图像

Javascript 上传后显示图像,javascript,jquery,ajax,asp.net-mvc-5,Javascript,Jquery,Ajax,Asp.net Mvc 5,我使用ajax上传文件工作了近3个小时,并成功地使其正常工作,请检查代码: 看法 JQuery/AJAX <script type="text/javascript"> $('#UploadFile').on('change', function (e) { var $this = $(this); var files = e.target.files; if (files.length > 0) {

我使用ajax上传文件工作了近3个小时,并成功地使其正常工作,请检查代码:

看法

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>
新图像大小

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中添加什么来动态添加图像而不刷新浏览器?

我会在成功函数中设置img标记usign jQuery的src属性:

  success: function (result) {
       $("img").attr('src' , '/path/to/your/img');
  },
如果您不知道客户端映像的公共路径,可以使用响应对象:

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

有几种可能性,使用哪种取决于图片大小等。 Personaly I(如果图像不是太大)会在服务器端将图像转换为OTBase64,并使用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
}

与Json一起
success
message返回图像的拇指路径/图像路径,并在
success
中将其呈现到
DOM
,或返回
模型本身。。如果可能,共享您的
SaveToFolder
code添加的SaveToFolder代码也
NewImageSize
method.)呵呵,我知道你在干什么了。来聊聊吧。。需要更多详细信息…好的,我会在我的控制器中将图像转换为base64,然后在ajax中如何工作?您只需从控制器base64编码值返回并插入html,如
div.html(“”)
hello guru我们可以在聊天室中发言吗我需要一些帮助无法创建房间
  success: function (result) {
       $("img").attr('src' , '/path/to/your/img');
  },
 return Json("{ path : "+model.ImagePath+"."+fileName+"."+extension+"}");
[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
}
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
     })
}