>  기사  >  웹 프론트엔드  >  Ajax로 이미지를 미리보고 업로드하고 썸네일을 보는 방법

Ajax로 이미지를 미리보고 업로드하고 썸네일을 보는 방법

php中世界最好的语言
php中世界最好的语言원래의
2018-04-03 15:08:541525검색

이번에는 ajax를 사용하여 이미지를 미리보기, 업로드 및 보기 썸네일을 보는 방법을 보여 드리겠습니다. ajax를 사용하여 이미지 미리보기, 업로드 및 보기를 위한 주의사항은 무엇입니까? 봐.

기능을 구현하려면 다른 텍스트가 있기 때문에 사진만 업로드하는 것이 아니라 다른 텍스트와 함께 저장하면 됩니다. ; 동시에 사진에 대한 썸네일이 생성됩니다. 이제 사진을 업로드하는 방법만 작성합니다. 여러 사진을 업로드하려면 텍스트 매개변수를 직접 전달하면 됩니다.

온라인 정보를 바탕으로 직접 작성했습니다. 페이지를 새로 추가할 필요도 없고 한 페이지만 있어도 됩니다.

JS 코드:

//ajax保存数据,后台方法里实现此方法 
function SaveData() {  
    filename = document.getElementById("idFile").value; 
    result =test_test_aspx.SaveData(filename).value; 
    if (result) { 
      alert("保存成功!");      
    } 
    return false; 
  }  
//实现预览功能 
  function DrawImage(ImgD) { 
    var preW = 118; 
    var preH = 118; 
    var image = new Image(); 
    image.src = ImgD.src; 
    if (image.width > 0 && image.height > 0) { 
      flag = true; 
      if (image.width / image.height >= preW/ preH) { 
        if (image.width > preW) { 
          ImgD.width = preW; 
          ImgD.height = (image.height * preW) / image.width; 
        } 
        else { 
          ImgD.width = image.width; 
          ImgD.height = image.height; 
        } 
        ImgD.alt = image.width + "x" + image.height; 
      } 
      else { 
        if (image.height > preH) { 
          ImgD.height = preH; 
          ImgD.width = (image.width * preH) / image.height; 
        } 
        else { 
          ImgD.width = image.width; 
          ImgD.height = image.height; 
        } 
        ImgD.alt = image.width + "x" + image.height; 
      } 
    } 
  } 
//当idFile内容改变时 
  function FileChange(Value) { 
    flag = false; 
    document.getElementById("showImg").style.display = "none";    
    document.getElementById("idImg").width = 10; 
    document.getElementById("idImg").height = 10; 
    document.getElementById("idImg").alt = ""; 
    document.getElementById("idImg").src = Value; 
  }

프론트엔드 코드는 다음과 같습니다.

<p class="cbs"> 
<p class="l"><label>图片:</label></p> 
<p> 
  <input id="idFile" name="pic" type="file" runat="server" onchange="FileChange(this.value);" /> 
</p> 
    </p>  
    <p class="cbs"> 
<p class="l"><label>预览:</label></p> 
<p> 
  <img id="idImg" height="0" width="0" src="" alt="" onload="DrawImage(this);" /> //实现预览 
  <img id="showImg" width="118" height="118" alt="" runat="server" style="display:none"/>  //加这个主要是为了实现查看时显示图片,因为上面的(idImg)加上runat="server" 报错,如有好的方法可以留言     
</p> 
</p>

AJAX 메서드는 다음과 같습니다.

[Ajax.AjaxMethod()] 
public bool SaveData(string fileNamePath) 
{ 
  string serverFileName = ""; 
  string sThumbFile = "";   
  string sSavePath = "~/Files/"; 
  int intThumbWidth = 118; 
  int intThumbHeight = 118; 
  string sThumbExtension = "thumb_"; 
  try 
  { 
 //获取要保存的文件信息 
 FileInfo file = new FileInfo(fileNamePath); 
 //获得文件扩展名 
 string fileNameExt = file.Extension; 
 
 //验证合法的文件 
 if (CheckFileExt(fileNameExt)) 
 { 
   //生成将要保存的随机文件名 
   string fileName = GetFileName() + fileNameExt; 
   //检查保存的路径 是否有/结尾 
   if (sSavePath.EndsWith("/") == false) sSavePath = sSavePath + "/"; 
 
   //按日期归类保存 
   string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/"; 
   if (true) 
   { 
 sSavePath += datePath; 
   } 
   //获得要保存的文件路径 
   serverFileName = sSavePath + fileName; 
   //物理完整路径 
   string toFileFullPath = HttpContext.Current.Server.MapPath(sSavePath); 
 
   //检查是否有该路径 没有就创建 
   if (!Directory.Exists(toFileFullPath)) 
   { 
 Directory.CreateDirectory(toFileFullPath); 
   } 
 
   //将要保存的完整文件名  
   string toFile = toFileFullPath + fileName; 
 
   ///创建WebClient实例 
   WebClient myWebClient = new WebClient(); 
   //设定windows网络安全认证  
   myWebClient.Credentials = CredentialCache.DefaultCredentials; 
   
   //要上传的文件 
   FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); 
   //FileStream fs = OpenFile(); 
   BinaryReader r = new BinaryReader(fs); 
   //使用UploadFile方法可以用下面的格式 
   //myWebClient.UploadFile(toFile, "PUT",fileNamePath); 
   byte[] postArray = r.ReadBytes((int)fs.Length); 
   Stream postStream = myWebClient.OpenWrite(toFile, "PUT"); 
   if (postStream.CanWrite) 
   { 
 postStream.Write(postArray, 0, postArray.Length); 
   } 
   postStream.Close(); 
   //以上为原图 
   try 
   { 
 //原图加载  
  using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(serverFileName))) 
 { 
   //原图宽度和高度  
   int width = sourceImage.Width; 
   int height = sourceImage.Height; 
   int smallWidth; 
   int smallHeight; 
 
   //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高)  
   if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight) 
   { 
  smallWidth = intThumbWidth; 
  smallHeight = intThumbWidth * height / width; 
   } 
   else 
   { 
  smallWidth = intThumbHeight * width / height; 
  smallHeight = intThumbHeight; 
   } 
 
   //判断缩略图在当前文件夹下是否同名称文件存在  
  int file_append = 0; 
   sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(fileName) + fileNameExt; 
 
   while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile))) 
   { 
  file_append++; 
  sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(fileName) + 
file_append.ToString() + fileNameExt; 
   } 
   //缩略图保存的绝对路径  
   string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile; 
 
   //新建一个图板,以最小等比例压缩大小绘制原图  
   using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight)) 
   { 
  //绘制中间图  
  using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) 
  { 
//高清,平滑  
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; 
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
g.Clear(Color.Black); 
g.DrawImage( 
sourceImage, 
new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight), 
new System.Drawing.Rectangle(0, 0, width, height), 
System.Drawing.GraphicsUnit.Pixel 
); 
  } 
  //新建一个图板,以缩略图大小绘制中间图  
  using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight)) 
  { 
//绘制缩略图  
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1)) 
{   
//高清,平滑  
  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; 
  g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
  g.Clear(Color.Black); 
  int lwidth = (smallWidth - intThumbWidth) / 2; 
  int bheight = (smallHeight - intThumbHeight) / 2; 
  g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth,intThumbHeight, GraphicsUnit.Pixel); 
  g.Dispose(); 
  bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg); 
   return true; 
   } 
  } 
   } 
 } 
   } 
   catch 
   { 
 //出错则删除  
 System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(serverFileName)); 
 return false; 
   } 
 } 
 else 
 { 
   return false; 
 } 
  } 
  catch (Exception e) 
  { 
 return false; 
  } 
} 
/// <summary> 
/// 检查是否为合法的上传文件 
/// </summary> 
/// <param name="_fileExt"></param> 
/// <returns></returns> 
private bool CheckFileExt(string _fileExt) 
{ 
  string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" }; 
  for (int i = 0; i < allowExt.Length; i++) 
  { 
 if (allowExt[i] == _fileExt) { return true; } 
  } 
  return false; 
 
} 
   //生成随机数文件名 
public static string GetFileName() 
{ 
  Random rd = new Random(); 
  StringBuilder serial = new StringBuilder(); 
  serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff")); 
  serial.Append(rd.Next(0, 999999).ToString()); 
  return serial.ToString(); 
 
}

에서 사례를 읽으신 후 메서드를 마스터하신 것 같습니다. 이 기사에서 더 흥미로운 내용을 보려면 온라인에서 PHP 중국어 관련 기사를 주목하세요!

추천 자료:

양식을 제출하고 ajax로 파일 업로드를 구현하는 방법

Ajax가 json 형식 데이터를 백그라운드로 전송할 때 오류를 처리하는 방법

위 내용은 Ajax로 이미지를 미리보고 업로드하고 썸네일을 보는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.