自己写的图片上传

该博客展示了如何实现一个简单的图片上传功能,每次仅允许上传一张图片,并且在上传新图片时会删除已有的图片。用户双击图片可以删除。功能实现涉及asp.net页面代码、后台处理和JavaScript交互,利用jQuery库进行交互增强。
摘要由CSDN通过智能技术生成

先看效果图:

 文件布局:

defualt.aspx代码:

<head runat="server">
    <title></title>
    <script src="script/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="script/jquery.form.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <table width="600">
        <tr>
            <td style="width: 150px; text-align: right;">
                用户名:
            </td>
            <td>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td style="width: 150px; text-align: right;">
                图片名称:
            </td>
            <td>
                <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td style="width: 150px; text-align: right;">
                图片:
            </td>
            <td>
                <asp:HiddenField ID="ImageHideFile" runat="server" />
                <div id="dvi" style="clear: both; margin-bottom: 5px;">
                </div>
                <span id="filespan">
                    <input type="file" name="file" id="FileUpload" />
                </span> 
                <input id="UploadButton" type="button" value="upload" />
            </td>
        </tr>
        <tr>
            <td colspan="2" style="padding-left: 160px">
                <asp:Button ID="Button4" runat="server" Text="Submit" OnClick="Button2_Click" />
            </td>
        </tr>
    </table>
    </form>

    <script src="script/JScript.js" type="text/javascript"></script>

</body>


default.aspx后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    webpublic wp = new webpublic();
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        wp.ShowMessageBox(ImageHideFile.Value);
        //wp.Show_Msg(ImageHideFile.Value);
    }
}


webpublic.cs主要代码:

 

/// <summary>
    /// 页面只弹出消息框,不跳转,不刷新!
    /// </summary>
    /// <param name="msg"></param>
    public void ShowMessageBox(string msg)
    {
        Page page = (Page)HttpContext.Current.CurrentHandler;
        page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + msg + "')</script>");
    }

/// <summary>
    /// 验证文件类型
    /// </summary>
    /// <param name="file">上传上来的文件</param>
    /// <returns></returns>
    public Boolean IsAllowedExtension(HttpPostedFile file)
    {
        int fileLen = file.ContentLength;
        byte[] imgArray = new byte[fileLen];
        file.InputStream.Read(imgArray, 0, fileLen);
        MemoryStream ms = new MemoryStream(imgArray);
        System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
        string fileclass = "";
        byte buffer;
        try
        {
            buffer = br.ReadByte();
            fileclass = buffer.ToString();
            buffer = br.ReadByte();
            fileclass += buffer.ToString();
        }
        catch
        {
        }
        finally
        {
            br.Close();
            ms.Close();
        }
        //说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
        if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")
            return true;
        else
            return false;
    }

// <summary>
    /// 提示成功信息!.back()
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="url"></param>
    public void Show_Msg(string msg)
    {

        HttpContext.Current.Response.Write("<script>alert(\"" + msg + "\");history.back();</script>");
        HttpContext.Current.Response.End();
    }

 

fileupload.aspx的后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class WebAdmin_fileupload : System.Web.UI.Page
{
    webpublic wp = new webpublic();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Files["file"] != null)
        {
            HttpPostedFile file = Request.Files["file"];
            //验证文件格式
            if (wp.IsAllowedExtension(file))
            {
                Random ra = new Random();
                String filePath = "~/Files/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ra.Next(1000, 9999)
                    //获取文件后缀
                    + System.IO.Path.GetExtension(file.FileName);
                try
                {
                    file.SaveAs(Server.MapPath(filePath));
                    Response.Write(ResolveUrl(filePath));
                }
                catch (Exception)
                {
                    Response.Write("文件上传发生错误!");
                }
            }
            else
            {
                Response.Write("文件格式不正确!");
            }
        }

        if (Request["myurl"] != null)
        {
            var url =Request["myurl"];
            try
            {
                System.IO.File.Delete(Server.MapPath(url));
                Response.Write("文件删除成功!");
            }
            catch (Exception)
            {
                Response.Write("文件删除失败!");
            }
        }
        Response.End();
    }
}

js代码部分: 

$(document).ready(function() {
    var img = document.createElement("img");
    img.title = "双击图片可删除图片";
    img.id = "UploadImg";
    img.height = "100";
    $("#UploadButton").click(function() {
        if ($("#FileUpload").val() == "") {
            alert("请选择要上传的图片!");
            return false;
        }
        //如果已有图片,则先把图片删除
        if ($("#ImageHideFile").val() != "") {
            $.get("fileupload.aspx?myurl=" + $("#ImageHideFile").val(),
            function(data) {
                $("#ImageHideFile").val("");
                $("#UploadImg").attr("src", "");
            });
        }
        var myform = document.createElement("form");
        myform.action = "fileupload.aspx";
        myform.method = "post";
        myform.enctype = "multipart/form-data";
        document.body.appendChild(myform);  //创建表单后一定要加上这句否则得到的form不能上传。                                               //document后要加上body,否则火狐下不行。
        var form = $(myform);
        var fu = $("#FileUpload").clone(true).val("");
        var fua = $("#FileUpload").appendTo(form);
        $("#filespan").html("<img src=\"images/loading.gif\" />   正在上传..  ");

        form.ajaxSubmit({
            success: function(data) {
                if (data == "文件上传发生错误!" || data == "文件格式不正确!") {
                    alert(data);
                }
                else {
                    $("#ImageHideFile").val(data);
                    $("#dvi").find("img").remove();
                    $("#dvi").append($(img));//要先append再给img赋值,否则在ie下不能缩小宽度
                    $(img).attr("src", data);                    
                 //绑定图片双击事件。实现双击图片删除图片
                    $(img).bind("dblclick",
                    function() {
                        if ($("#ImageHideFile").val() == "") {
                            return;
                        }
                        $.get(
                            "fileupload.aspx?myurl=" + $("#ImageHideFile").val(),
                            function(data) {
                                alert(data);
                                if (data == "文件删除成功!") {
                                    $("#ImageHideFile").val("");
                                    $(img).remove();
                                }
                                $("#UploadImg").attr("src", $("#ImageHideFile").val());
                            });
                    });
                }
                $("#filespan").html(fu);
                form.remove();
            }
        });
    });
});


每次只能上传一张图片。每次上传时如果已经有图片则把原图删除再上传,上传后双击图片可删除图片。适合用于只上传一张图片。

引用了这两个类库

<script src="script/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="script/jquery.form.js" type="text/javascript"></script>

2011年9月13日 改进版本请看:http://blog.csdn.net/weizengxun/article/details/6769977


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A:Spring Boot可以很容易地实现图片上传和下载功能。下面是一个简单的示例代码,演示了如何处理图像上传和下载。 1. 图片上传功能 创建一个Spring Boot Controller类,处理图像上传请求: ``` @RestController @RequestMapping("/api/image") public class ImageController { @PostMapping("/upload") public String uploadImage(@RequestParam("file") MultipartFile file) { try { // 保存图片到本地磁盘或云存储 byte[] bytes = file.getBytes(); // ...保存图片代码... return "上传成功!"; } catch (IOException e) { e.printStackTrace(); return "上传失败!"; } } } ``` 2. 图片下载功能 同样创建一个Spring Boot Controller类,处理图像下载请求: ``` @RestController @RequestMapping("/api/image") public class ImageController { @GetMapping("/download") public ResponseEntity<byte[]> downloadImage() { try { // 获取要下载的图片文件 String fileName = "test.jpg"; File file = new File(fileName); // 将图片文件转换为字节数组 FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[fis.available()]; fis.read(bytes); fis.close(); // 设置HTTP响应头,表明响应类型为图片 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); headers.setContentDisposition( ContentDisposition.builder("attachment") .filename(fileName) .build()); // 返回图片字节数组 return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return null; } } } ``` 以上是基本的示例代码,您可以根据需求进行更改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值