服务器上的图像上传问题

时间:2013-10-30 08:59:26

标签: javascript jquery asp.net

请帮我解决以下问题:

这是我的代码: ASPX代码:

<input type="Button" id="BtnUpload" class="button1" value="Upload Image" onclick="clickFileUpload();" />

ASPX页面上的Javascript函数:

function UploadImage(path) //Added by Archana on 14-Aug-2013
{         

 var Sketch_Code,url,str;
 Sketch_Code= document.getElementById('<%=txtCode.ClientID%>').value;
 var strPage,strWidthProperty ;
 var retVal=""; 
 if(Sketch_Code !="")
 {
   if(path!="" && path!=null)
  {
//  var timeout = setTimeout("Imageresize(path,Sketch_Code);", 5000);
//  alert(timeout);
  var img = Imageresize(path,Sketch_Code);
  if (document.getElementById('<%=imgload.ClientID%>').complete) 
  {alert("loaded");
  url = "<%= ConfigurationManager.AppSettings("SiteURL").ToString() %>Upload_Images/800x800/" ;
   document.getElementById('<%=imgload.ClientID%>').src =url + img;
   document.getElementById('<%=imagePath.ClientID%>').value=img;
  }

  }
}
}

function clickFileUpload() 
 {
      $('input[type=file]:first').trigger('click');
      var imgpath=document.getElementById("imgfile").value;
         //alert(imgpath);
           if(imgpath =='') 
          {
            // There is no file selected 
            alert("Please select valid file.");
          }
          else
          {
            var Extension = imgpath.substring(imgpath.lastIndexOf('.') + 1).toUpperCase();
            if (Extension == "BMP" || Extension == "JPG" || Extension == "JPEG" || Extension == "GIF" || Extension == "PNG" )
            {
                UploadImage(imgpath);// Valid file type          
            }
            else
            {
             // Not valid file type
                  alert("Please select valid extension file. (.bmp,.jpeg,.jpg,.png,.gif)");
            }
           }
}

 function Imageresize(e,c)
{
    //alert(e.id);
    var Imagename = e; 
    var Code=c;
    $.ajax({async : false, 
                  type : 'GET', /*callback: function(index){CalculateTotal()},*/
                  url : "ImageResizer.aspx?Sketch_Code="+ c +"&imagepath=" + e, 
                  success : function(response)
                    {
                        setTimeout('checkForAllImagesLoaded()', 5);
                        ImagesString = response;
                        // var ArrValues = ImagesString.split("~");


                    }

            });
     return ImagesString;        
}

这是我在ImageResizer页面上的代码:

Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D

Partial Class ImageResizer
    Inherits System.Web.UI.Page
    Public Shared Function ResizeImage(ByVal image As Image, ByVal path As String, ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True) As Image
        Dim newWidth As Integer
        Dim newHeight As Integer
        If preserveAspectRatio Then
            Dim originalWidth As Integer = image.Width
            Dim originalHeight As Integer = image.Height
            Dim percentWidth As Single = CSng(size.Width) / CSng(originalWidth)
            Dim percentHeight As Single = CSng(size.Height) / CSng(originalHeight)
            Dim percent As Single
            percent = IIf(percentHeight < percentWidth, percentHeight, percentWidth)
            newWidth = CInt(originalWidth * percent)
            newHeight = CInt(originalHeight * percent)
        Else
            newWidth = size.Width
            newHeight = size.Height
        End If
        Dim newImage As Image = New Bitmap(newWidth, newHeight)
        Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
            graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
            graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight)
        End Using
        newImage.Save(path)
        Return newImage
    End Function

    Function UploadFileToServer(ByVal filepath As String, ByVal code As String) As String
        Dim scriptStr As String = ""
        Dim FileName As String
        Try
            Dim fileExtension As String = Path.GetExtension(filepath).ToLower()
            FileName = code.Trim() + DateTime.Today.ToShortDateString().Replace("/", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + fileExtension
            File.Copy(filepath, Server.MapPath("Upload_Images/") & FileName)

        Catch ex As Exception

        End Try
        Return FileName
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim filepath, resizedpath, code As String
        filepath = Request.QueryString("imagepath")
        code = Request.QueryString("Sketch_Code")
        If filepath <> "" Then
            filepath = UploadFileToServer(filepath, code)
            Dim original As Image = Image.FromFile(Server.MapPath("Upload_Images/") & filepath)
            resizedpath = Server.MapPath("Upload_Images/200X200/") & filepath
            ResizeImage(original, resizedpath, New Size(200, 200))
            resizedpath = Server.MapPath("Upload_Images/800X800/") & filepath
            ResizeImage(original, resizedpath, New Size(800, 800))
            Response.Expires = -1
            Response.ContentType = "text/plain"
            Response.Write(filepath.ToString())
            Response.End()
        End If


    End Sub
End Class

此代码在我的本地(开发环境)上正常运行 但是当我在服务器上部署此代码后尝试上传时,我的代码不适用于$ .ajax函数。无法获得返回我的imagestring的响应。

请帮忙

1 个答案:

答案 0 :(得分:0)

它会返回你,GDI错误。 ?

对于GDI错误请参阅:

这是因为缺少“Upload_Images /”目录。

所以要获得正确的位置

您必须在Catch块中编写以下代码才能打印

 Response.Write(Server.MapPath("Upload_Images/"));

这将返回Upload_Images文件夹的正确路径。