我网上找了一个上传图片的方法,是用jquery和ajax实现无刷新上传。通过一个ashx文件来处理图片上传,在ashx文件中对上传文件进行了重命名。在图片上传页面使用如下脚本:
<script type="text/javascript">
function upLogo() {
$.ajax
({
type: "POST",
url: "AjaxUpPIC.ashx",
data: { upfile: getPath($("#File")) },
success: function (data) {
alert(data);
}
});
}
</script>
来上传,我试过了,可以上传。可是怎么能在页面后台中得到更改后的文件名呢
<script type="text/javascript">
function upLogo() {
$.ajax
({
type: "POST",
url: "AjaxUpPIC.ashx",
data: { upfile: getPath($("#File")) },
success: function (data) {
alert(data);
}
});
}
</script>
来上传,我试过了,可以上传。可是怎么能在页面后台中得到更改后的文件名呢
你看看 把返回值改成图片名称就然后前台alert一下看看
我也不太熟悉ajax 好像data就是成功后的返回值
"AjaxUpPIC.ashx
里面
context.Response.Write()出来
alert(data);
}
这里alert出来的是什么?
lbl解析以后是span标签,ID不对吧。。
那代码出来看看。。
success: function (data) {
document.getElementById("<%=Label1.ClientID%>").innerHTML= data;
}
{
String savePath = Server.MapPath("/BookCover/");
if (FileUpload1.HasFile)
{
// Get the name of the file to upload.
String fileName = FileUpload1.FileName;
int fileSize = FileUpload1.PostedFile.ContentLength;
string extension = System.IO.Path.GetExtension(fileName);
if (!(extension == ".jpg" || extension == ".JPG"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('图片格式错误,应为.jpg格式!图书信息保存失败!')", true);
return false;
}
int index = fileName.LastIndexOf(".");
string type = fileName.Substring(index).ToLower();//取文件的扩展名
string newName = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");//声称文件名,防止重复
newName = newName + type;
if (fileSize < 2097152)
{ // Append the name of the file to upload to the path.
savePath += newName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath); // Notify the user of the name of the file
// was saved under.
//txtCoverPhoto.Text = "/BookCover/" + newName;
CoverPath = "/BookCover/" + newName;
//imgCoverPhoto.ImageUrl = txtCoverPhoto.Text.Trim();
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('图书照片上传成功!')", true);
return true;
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('图书照片超过2M,上传失败!图书信息保存失败!')", true);
return false;
}
}
else
{
// Notify the user that a file was not uploaded.
//txtIntro.Text = "You did not specify a file to upload.";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('图书照片上传失败!图书信息保存失败!')", true);
return true ;
}
}