图片上传

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片上传相关的知识,希望对你有一定的参考价值。

 

 

 

 

一,效果

技术分享

二,材料
html

技术分享
<div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">图片:</h3>
                </div>
                <div class="panel-body">

                    <div class="img-box full">
                        <section class="img-section">
                            <p class="up-p"><span class="up-span">最多可以上传5张图片,马上上传。</span></p>
                            <div class="z_photo upimg-div clear">
                                <!--<section class="up-section fl">
                                <span class="up-span"></span>
                                <img src="/img/buyerCenter/a7.png" class="close-upimg">
                                <img src="/img/buyerCenter/3c.png" class="type-upimg" alt="添加标签">
                                <img src="/img/test2.jpg" class="up-img">
                                <p class="img-namep"></p>
                                <input id="taglocation" name="taglocation" value="" type="hidden">
                                <input id="tags" name="tags" value="" type="hidden">
                            </section>-->
                                @if (Model.Item1 != null && Model.Item1.Images != null)
                                {

                                    foreach (var path in Model.Item1.Images)
                                    {
                                        <section class="up-section fl" id="[email protected]">
                                            <span class="up-span"></span>
                                            <img src="/Scripts/imgup/a7.png" class="close-upimg">
                                            @*<img src="/img/buyerCenter/3c.png" class="type-upimg" alt="添加标签">*@
                                            <img src="@path.Item2" class="up-img">
                                            <p class="img-namep"></p>
                                            @*<input id="taglocation" name="taglocation" value="" type="hidden">
                                            <input id="tags" name="tags" value="" type="hidden">*@
                                        </section>
                                    }
                                }


                                <section class="z_file fl">
                                    <img src="~/Scripts/imgup/a11.png" class="add-img" />
                                    @*<img src="a_data/a11.png" class="add-img">*@
                                    <input name="file" id="file" class="file" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" multiple="" type="file">
                                </section>
                            </div>
                        </section>
                    </div>
                    <aside class="mask works-mask">
                        <div class="mask-content">
                            <p class="del-p">您确定要删除作品图片吗?</p>
                            <p class="check-p"><span class="del-com wsdel-ok">确定</span><span class="wsdel-no">取消</span></p>
                        </div>
                    </aside>

                    @*<input id="uploadFile" name="uploadFile" type="file" class="file" multiple data-preview-file-type="any">
                      @if (Model.Item1.Images != null){

                    foreach (string path in Model.Item1.Images)
                       {
                        <input type="hidden" class="oldimage" name="oldimage"  value="@path">
                       }
                      }*@
                </div>
            </div>
View Code

css

技术分享
/*上传图片插件的样式*/
.img-box{
    margin-top: 40px;
}
.img-box .up-p{
    margin-bottom: 20px;
    font-size: 16px;
    color: #555;
}
.z_photo{
    padding: 18px;
    border:2px dashed #E7E6E6;
    /*padding: 18px;*/
}
.z_photo .z_file{
    position: relative;
}
.z_file  .file{
    width: 100%;
    height: 100%;
    opacity: 0;
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 100;
}
.z_photo .up-section{
    position: relative;
    margin-right: 20px;
    margin-bottom: 20px;
}
.up-section .close-upimg{
    position: absolute;
    top: 6px;
    right: 8px;
    display: none;
    z-index: 10;
}
.up-section .up-span{
    display: block;
    width: 100%;
    height: 100%;
    visibility: hidden;
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 9;
    background: rgba(0,0,0,.5);
}
.up-section:hover{
    border: 2px solid #f15134;
}
.up-section:hover .close-upimg{
    display: block;
}
.up-section:hover .up-span{
    visibility: visible;
}
.z_photo .up-img{
    display: block;
    width: 100%;
    height: 100%;
}
.loading{
    border: 1px solid #D1D1D1;
    background:url(/Scripts/imgup/loading.gif) no-repeat center;
}
.up-opcity{
    opacity: 0;
}
.img-name-p{
    display: none;
}
.upimg-div .up-section {
    width: 190px;
    height: 180px;
}
.img-box .upimg-div .z_file {
    width: 190px;
    height: 180px;
}
.z_file .add-img {
    display: block;
    width: 190px;
    height: 180px;
}
View Code
技术分享
/*遮罩层样式*/
.mask{
    z-index: 1000;
    display: none;
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,.4);
}
.mask .mask-content{
     width: 500px;
     position: absolute;
     top: 50%;
     left: 50%;
     margin-left: -250px;
     margin-top: -80px;
     background: white;
     height: 160px;
     text-align: center;
}
.mask .mask-content .del-p{
    color: #555;
    height: 94px;
    line-height: 94px;
    font-size: 18px;
    border-bottom: 1px solid #D1D1D1;
}
.mask-content .check-p{
    height: 66px;
    line-height: 66px;
    position: absolute;
    bottom: 0px;
    left: 0px;
    width: 100%;
}
.mask-content .check-p span{
    width: 49%;
    display:inline-block;
    text-align: center;
    color:#d4361d ;
    font-size: 18px;
}
.check-p .del-com{
    border-right: 1px solid #D1D1D1;
}
View Code

图片

技术分享 技术分享

技术分享

 

javascript

技术分享
$(function(){
    var delParent;
    var defaults = {
        fileType         : ["jpg","png","bmp","jpeg"],   // 上传文件的类型
        fileSize         : 1024 * 1024 * 10                  // 上传文件的大小 10M
    };
        /*点击图片的文本框*/
    $(".file").change(function(){
        var idFile = $(this).attr("id");
        var file = document.getElementById(idFile);
        var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
        var fileList = file.files; //获取的图片文件
        console.log(fileList+"======filelist=====");
        var input = $(this).parent();//文本框的父亲元素
        var imgArr = [];
        //遍历得到的图片文件
        var numUp = imgContainer.find(".up-section").length;
        var totalNum = numUp + fileList.length;  //总的数量
        if(fileList.length > 5 || totalNum > 5 ){
            alert("上传图片数目不可以超过5个,请重新选择");  //一次选择上传超过5个 或者是已经上传和这次上传的到的总数也不可以超过5个
        }
        else if(numUp < 5){
            fileList = validateUp(fileList);
            for(var i = 0;i<fileList.length;i++){
             var imgUrl = window.URL.createObjectURL(fileList[i]);
                 imgArr.push(imgUrl);
                 var $section = $("<section class=‘up-section fl loading‘ id=‘img_" + fileList[i].imageid + "‘>");
                 imgContainer.prepend($section);
             var $span = $("<span class=‘up-span‘>");
                 $span.appendTo($section);
            
             var $img0 = $("<img class=‘close-upimg‘>").on("click",function(event){
                    event.preventDefault();
                    event.stopPropagation();
                    $(".works-mask").show();
                    delParent = $(this).parent();
                });   
                $img0.attr("src","/Scripts/imgup/a7.png").appendTo($section);
             var $img = $("<img class=‘up-img up-opcity‘>");
                 $img.attr("src",imgArr[i]);
                 $img.appendTo($section);
             var $p = $("<p class=‘img-name-p‘>");
                 $p.html(fileList[i].name).appendTo($section);
             //var $input = $("<input id=‘taglocation‘ name=‘taglocation‘ value=‘‘ type=‘hidden‘>");
             //    $input.appendTo($section);
             //var $input2 = $("<input id=‘tags‘ name=‘tags‘ value=‘‘ type=‘hidden‘/>");
             //    $input2.appendTo($section);
              
           }
        }
        setTimeout(function(){
             $(".up-section").removeClass("loading");
              $(".up-img").removeClass("up-opcity");
         },450);
         numUp = imgContainer.find(".up-section").length;
        if(numUp >= 5){
            $(this).parent().hide();
        }
        
        //input内容清空
        $(this).val("");
    });
    
    
   
    $(".z_photo").delegate(".close-upimg", "click", function () {
    //  alert(1);
           $(".works-mask").show();
           delParent = $(this).parent();
    });
        
    $(".wsdel-ok").click(function () {
      //  alert(2);
        $(".works-mask").hide();
        var numUp = delParent.siblings().length;
        if(numUp < 6){
            delParent.parent().find(".z_file").show();
        }

        //alert(delParent.attr("id"))
        var dataid = "id=" + delParent.attr("id").split(‘_‘)[1];
        $.ajax({
            url: ‘/Home/PicDel‘,
            type: ‘post‘,
            data: dataid,
            async: false,
            cache: false,           
            success: function (res) {

                delParent.remove();

            }
        });
        //$("#imagesdata").val();
        
        
    });
    
    $(".wsdel-no").click(function () {
      // alert(3);
        $(".works-mask").hide();
    });
        
        function validateUp(files){
            var arrFiles = [];//替换的文件数组
          
            for(var i = 0, file; file = files[i]; i++){
                //获取文件上传的后缀名
                var newStr = file.name.split("").reverse().join("");
                if(newStr.split(".")[0] != null){
                        var type = newStr.split(".")[0].split("").reverse().join("");
                        console.log(type+"===type===");
                        if(jQuery.inArray(type, defaults.fileType) > -1){
                            // 类型符合,可以上传
                            if (file.size >= defaults.fileSize) {
                                alert(file.size);
                                alert(‘您这个"‘+ file.name +‘"文件大小过大‘);    
                            } else {
                                // 在这里需要判断当前所有文件中
                               
                                var formData = new FormData();
                                formData.append(‘files‘, file);
                                formData.append(‘uuid‘, $("#uuid").val());
                                $.ajax({
                                    url: ‘/Home/FileInput‘,
                                    type: ‘post‘,
                                    data: formData,
                                    async: false,
                                    cache: false,
                                    contentType: false,
                                    processData: false,
                                    success: function (res) {
                                        file.imageid = res.item1;
                                        arrFiles.push(file);
                                    
                                    }
                                });
                              


                            }
                        }else{
                            alert(‘您这个"‘+ file.name +‘"上传类型不符合‘);    
                        }
                    }else{
                        alert(‘您这个"‘+ file.name +‘"没有类型, 无法识别‘);    
                    }
            }

        
            return arrFiles;
        }
        
    
})
View Code

后端C#

技术分享
  [HttpPost]
        public ActionResult FileInput()
        {
            try
            {
                var files = Request.Files;
                if (files != null && files.Count > 0)
                {
                    List<int> imagesid = new List<int>();
                    if (Session["GoodImages"] != null)
                    {

                        imagesid = (List<int>)Session["GoodImages"];
                    }

                    int i = 0;
                    var file = files[i];
                    string fileName = file.FileName;
                    string fileRelName = Request["uuid"]; //fileName.Substring(0, fileName.LastIndexOf(‘.‘));//设置临时存放文件夹名称
                    string index = Guid.NewGuid().ToString(); // Convert.ToInt32(Request["chunk"]);//当前分块序号
                                                              //  var guid = Request["guid"];//前端传来的GUID号
                    var dir = Server.MapPath("~/Upload");//文件上传目录
                    dir = Path.Combine(dir, fileRelName);//临时保存分块的目录
                    if (!System.IO.Directory.Exists(dir))
                        System.IO.Directory.CreateDirectory(dir);
                    string filePath = Path.Combine(dir, index.ToString() + fileName.Substring(fileName.LastIndexOf(.)));//分块文件名为索引名,更严谨一些可以加上是否存在的判断,防止多线程时并发冲突
                    var data = file;//表单中取得分块文件
                                    //if (data != null)//为null可能是暂停的那一瞬间
                                    //{
                    data.SaveAs(filePath);//报错
                                          //}

                    GoodImages gi = new GoodImages();
                    gi.ImagePath = filePath;
                    gi.Name = fileName;
                    GoodImagesService.Insert<GoodImages>(gi);
                    imagesid.Add(gi.Id);



                    if (Session["GoodImages"] != null)
                    {
                        Session["GoodImages"] = imagesid;
                    }
                    else
                    {
                        Session.Add("GoodImages", imagesid);
                    }

                    JsonResult jr = new JsonResult();
                    jr.Data = new { item1 = gi.Id };
                    return jr;
                }
                else
                {
                    JsonResult jr = new JsonResult();
                    jr.Data = new { item1 = 0 };
                    return jr;
                }
            }
            catch (Exception ex)
            {
                JsonResult jr = new JsonResult();
                jr.Data = new { item1 = 0 };
                return jr;

            }

        }
View Code

 




以上是关于图片上传的主要内容,如果未能解决你的问题,请参考以下文章

使用 AFNetworking、ios 上传图片

Android - 应用程序启动时片段 onCreate 崩溃

手机safari图片上传竖变横处理

java Ftp上传创建多层文件的代码片段

根据图片的url地址下载图片到本地保存代码片段

如何将CKeditor编辑器的上传和thinkphp结合