-2

当我尝试执行代码时,我试图通过回调方法将图像保存在服务器上我得到异常演示代码示例:http ://catalog.codeproject.com/Articles/17193/Upload-Images-Using-C-JavaScript-and- ASP-NET-2-0-C

流 s = File.OpenRead(returnValue); 在cs文件中我得到异常文件未找到

  <input id="File1" runat="server"  onchange="PopulateList(this)" name="File1" type="File" />

<script language="javascript" type="text/javascript">

    var counter = 1;
    var newPath = '';
    var filePath = '';


    function PopulateList(obj) {
        // Upload the image to the server folder 
        filePath = obj.value;
        // calls the server's method using client callbacks    
        CallServer(obj.value, '');
    }

    function ReceiveServerData(rValue) {

        // The new path will contain the path of the image which is inside the server's folder 
        newPath = rValue;
        alert(newPath);
        //CreateNestedElements();

    }
</script>

在 Cs 文件中

protected string returnValue = String.Empty;

protected void Page_Load(object sender, EventArgs e)
{
    string[] filePaths = null;

    //HtmlInputHidden hiddenControl = (HtmlInputHidden)Page.FindControl("list");
    //if (!String.IsNullOrEmpty(hiddenControl.Value))
    //{
    //    filePaths = hiddenControl.Value.Split('|');

    //    //SaveFilesToDB(filePaths);

    //}

    // register the callback script 

    string sbReference = ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");

    string cbScript = String.Empty;

    // check if the script is already registered or not 

    if (!ClientScript.IsClientScriptBlockRegistered("CallServer"))
    {

        cbScript = @" function CallServer(arg,context) { " + sbReference + "}";

        ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);

    }
}


public string GetCallbackResult()
{
    string fileName = System.IO.Path.GetFileName(returnValue);

    string path = Server.MapPath("Images/");
    string fullPath = path + fileName;

    Stream s = File.OpenRead(returnValue);

    byte[] buffer = new byte[s.Length];
    s.Read(buffer, 0, (int)s.Length);

    int len = (int)s.Length;

    s.Dispose();
    s.Close();

    FileStream fs = new FileStream(fullPath, FileMode.Create);
    fs.Write(buffer, 0, len);

    Bitmap bmp = new Bitmap(fs);


    if (System.IO.Path.GetExtension(returnValue).Equals(".gif"))
    {
        bmp.Save(fs, ImageFormat.Gif);
    }
    else
    {
        bmp.Save(fs, ImageFormat.Jpeg);
    }

    bmp.Dispose();

    fs.Dispose();
    fs.Close();                      

    return "Images/" + fileName;
}

public void RaiseCallbackEvent(string eventArgument)
{
    if (!String.IsNullOrEmpty(eventArgument))
    {
        returnValue = eventArgument;
    }
}
4

1 回答 1

1

不幸的是,您链接的代码项目文章完全是垃圾 - 只有当您使用与客户端和服务器相同的机器并且仅在 Internet Explorer 中,该代码才能工作。在其他情况下,您一定会遇到异常,因为已发送到服务器的文件路径将是客户端计算机上的本地文件路径,并且不会出现在服务器计算机上(File.OpenRead由于路径在服务器上无效而导致失败) .

我不确定你想要达到什么 - 如果你想异步上传文件,你会发现很多插件或示例。例如,您可能使用 AJAX 工具包的 AsyncFileUpload控件。

于 2013-01-08T10:09:26.400 回答