通过javascript使用回调发送图像到服务器
本文关键字:图像 服务器 回调 javascript 通过 | 更新日期: 2023-09-27 17:50:55
我试图通过回调方法在服务器上保存图像,当我尝试执行代码时,我得到异常演示代码示例: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>
In Cs File
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;
}
}
不幸的是,您链接的代码项目文章完全是垃圾-代码只有在客户端和服务器使用同一台机器时才能工作,而且也只能在internet explorer中工作。在其他情况下,您必然会得到一个异常,因为已经发送到服务器的文件路径将是客户端机器上的本地文件路径,而不会出现在服务器机器上(导致File.OpenRead
失败,因为服务器上的路径无效)。
我不确定你想要实现什么-你会发现大量的插件或样本,如果你想异步上传文件。例如,您可以使用AJAX工具包AsyncFileUpload控件。