附件上传功能-01

1、前台页面

1 <div class="input-group" style="width:100%">
2                             <input type="file" id="file" name="myfile"  class="form-control" />
3                             <span class="input-group-btn">
4                                 <button id="btn-fileUpload" class="btn btn-success" type="button">上传</button>
5                             </span>
6                         </div>
7                         <div style="display:none;" id="div-progress"><progress id="progressBar" value="0" max="100"></progress><span id="percentage"></span></div>

css样式基于
Bootstrap v3.3.7 (http://getbootstrap.com)

2、JavaScript Code

$("#btn-fileUpload").on('click', function () {
                    var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
                    var FileController = settings.apiUrl + "/Version/UploadFile"; // 接收上传文件的后台地址
                    // FormData 对象
                    var form = new FormData();
                    // form.append("author", "hooyes");                        // 可以增加表单数据
                    form.append("file", fileObj);                           // 文件对象
                    // XMLHttpRequest 对象
                    var xhr = new XMLHttpRequest();
                    xhr.open("post", FileController, true);
                    xhr.onload = function (result) {
                        var response = $.parseJSON(result.target.response);
                        $("#hidPathUrl").val("/Upload/Version/" + response.context);
                        tincher.message(response.message);
                    };
                    xhr.upload.addEventListener("progress", function (evt) {
                        $("#div-progress").show();
                        var progressBar = document.getElementById("progressBar");
                        var percentageDiv = document.getElementById("percentage");
                        if (evt.lengthComputable) {
                            progressBar.max = evt.total;
                            progressBar.value = evt.loaded;
                            percentageDiv.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
                        }
                    }, false);
                    xhr.send(form);
                });

3、C# API

        /// <summary>
        /// 数据包、app应用安装包上传
        /// </summary>
        /// <param name="imageid">categroy由前端传过来</param>
        /// <returns></returns>
        [AllowAnonymousAttribute]//允许所有请求
        [HttpPost]
        [Route("api/Version/UploadFile")]
        public HttpResponseMessage UploadFile()
        {
            try
            {

                HttpRequest request = System.Web.HttpContext.Current.Request;
                HttpFileCollection fileCollection = request.Files;
                if (fileCollection.Count > 0)
                {
                    //获取WebApi项目根目录指定的文件夹(记住要给IUSER完全的控制权限,这样IIS才能把文件写到那个文件夹)
                    string uploadFolderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Upload/Version/");

                    //如果路径不存在,创建路径
                    if (!Directory.Exists(uploadFolderPath))
                        Directory.CreateDirectory(uploadFolderPath);
                    // 获取文件
                    HttpPostedFile httpPostedFile = fileCollection[0];
                    string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
                    string fileName = httpPostedFile.FileName;// 名称
                    if (fileName.Contains("\\"))
                    {
                        var arr = fileName.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                        fileName = arr[arr.Length - 1];
                    };
                    var exts = fileName.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                    var ext = exts[exts.Length - 1];
                    var strs = new string[] { "apk", "zip" };
                    if (!strs.Contains(ext))
                    {
                        return Error(0, "上传失败", "只允许上传apk、zip格式文件");
                    }
                    string filePath = uploadFolderPath + fileName;// 上传路径
                    httpPostedFile.SaveAs(filePath);
                    return Success(1, "上传成功", fileName);
                }
                else
                {
                    return Error(0, "上传失败", null);
                }
            }
            catch (Exception ex)
            {
                LogManager.GetInstance("txt").Error("上传异常->" + ex.Message);
                return Error(0, "发生异常", ex.Message);
            }
        }

 

posted @ 2020-10-27 10:41  Coderlhx  阅读(402)  评论(0编辑  收藏  举报