<th id="v9g6b"><track id="v9g6b"></track></th>

  • <em id="v9g6b"><acronym id="v9g6b"></acronym></em>
    <progress id="v9g6b"><pre id="v9g6b"></pre></progress>
    <tbody id="v9g6b"></tbody>
    <button id="v9g6b"><acronym id="v9g6b"></acronym></button>
    <rp id="v9g6b"><ruby id="v9g6b"></ruby></rp>

        <dd id="v9g6b"></dd>

        <em id="v9g6b"></em>

          软件开发平台文件上传下载

          软件开发平台文件上传下载,比如上传一个图片到服务器上,直接做为字符串形式保存到数据库不行吗?

          软件开发平台上传

          如果存在大量(海量)图片需要保存时,保存到数据库就不行了,为什么?想象数据库里面保存了海量数据是什么概念,是不是会拖累其他的数据的操作,所以我们把这些文件直接保存到服务器硬盘上,这样就好了。下面是我们的图片上传组件:


          @model string
          @{
              var filePath = System.Configuration.ConfigurationManager.AppSettings["filePath"] + Convert.ToString(ViewData["FilePath"] ?? "certificate/");/*上传路径*/
              //bool state = true;// ViewData["state"] != null ? (bool)ViewData["state"] : true; /*清楚图片时是否保留路径*/
              bool displayImage = ViewData["DisPlay"] != null ? (bool)ViewData["DisPlay"] : true; /*是否显示图片*/
              bool customImage = ViewData["CustomImage"] != null ? (bool)ViewData["CustomImage"] : true; /*是否显示自定义图片*/
              var fullId = ViewData.TemplateInfo.GetFullHtmlFieldId("");
              var fullName = ViewData.TemplateInfo.GetFullHtmlFieldName("") + Guid.NewGuid();
              string editShow = Model == null ? " hidden" : "";
              string createShow = Model != null ? " hidden" : "";
              string serverType = (ViewData["ServerType"]!=null?Convert.ToString(ViewData["ServerType"]):"");
          }
          <p tp="p_uploadImg" style="position:relative;" maxSize="@(System.Configuration.ConfigurationManager.AppSettings["PicMaxSize"])">
              <input id="PicPathList" name="PicPathList" type="hidden" value="@Model">
              <span class="spanname" style="padding-top: 40px; padding-bottom: 50px;">
              @Html.LabelFor(w => w):</span>
              @if (displayImage)
              {
                  <img src="@(Model != null ? Model : "/content/images/wechat.png")" displayimage="@displayImage" tp="defaultPic" alt="" id="pic@(fullId)" width="110" height="110" />
              }
              @Html.TextBoxFor(w => w, new { style = "border:0;width:0", tp = "hidden" })
          
              @*自定义文件路径*@@Html.TextBox("cfilePath", Model, new { @class = "input1" + editShow,@style="width:0;height:0;" })
          
              <input id="file@(fullId)" name="file@(fullName)" style="height: 35px; width: 60px; position: absolute; top: 75px; opacity: 0; left: 273px; *left: 260px; cursor: pointer; filter: alpha(opacity=0);" class="input1" type="file" title="@(Model==null?"上传":"修改")图片" />
          
              <input class="btn_up" value="@(Model==null?"上传":"修改")图片" tp="uploadImg" servertype="@serverType" specialpath="@filePath" id="btn_upload@(fullId)" type="button" onmouseover="floatFile(this)" />
              @*<input type="button" id="btn_clear@(fullId)" state="@state.ToString()" servertype="@serverType" value="清除" class="btn_up@(editShow)" />*@
              <br />
              <i class="tips">
                  (图片大小不能超过@(System.Configuration.ConfigurationManager.AppSettings["PicMaxSize"])M)
              </i>
              @Html.ValidationMessageFor(w => w)
          </p>
          核心代码是这两个input组件,一个type为file,一个是按钮,通过按钮的点击事件去异步提交文件给后台,后台再通过网络传输文件给文件服务器的服务程序,


           <input id="file@(fullId)" name="file@(fullName)" style="height: 35px; width: 60px; position: absolute; top: 75px; opacity: 0; left: 273px; *left: 260px; cursor: pointer; filter: alpha(opacity=0);" class="input1" type="file" title="@(Model==null?"上传":"修改")图片" />
           <input class="btn_up" value="@(Model==null?"上传":"修改")图片" tp="uploadImg" servertype="@serverType" specialpath="@filePath" id="btn_upload@(fullId)" type="button" onmouseover="floatFile(this)" />
          javascript脚本如下:


          <script src='/Scripts/jquery.form.js' type='text/javascript'></script>
              <script type="text/javascript">
                  $(document).ready(function () {
                      $(".btn_up").bind("click", function () {
                          upLoadImg();
                      });
                  });
                  function upLoadImg() {
                      var accBtn = $(this).nextAll("input:button[tp=uploadImg]").eq(0);
                      var accFile = $(this);
                      var filePath = accFile.val();
                      var sizestyle = accBtn.parent().find(".tips").attr("sizestyle"); //获取尺寸字符串
                      if (filePath.length > 0) {
                          if (!(filePath.toLowerCase().indexOf(".gif", 0) != -1 || filePath.toLowerCase().indexOf(".jpg", 0) != -1 || filePath.toLowerCase().indexOf(".png", 0) != -1)) {
                              alert('上传图片必须为jpg、gif、png格式文件');
                          }
                          else {
                              $(this.form).ajaxSubmit({
                                  url: "@Url.Action("Uploadfile", "UpLoadControl")",
                                  data: { "filepath": accBtn.attr("specialPath"), "fileName": accFile.attr("name"), "serverType": accBtn.attr("serverType"), "sizestyle": sizestyle },
                                  dataType: "text",
                                  type:"POST",
                                  success: function (json) {
                                      responseText = eval("(" + json + ")");
                                      if (responseText.Detail == "error" || responseText.Code < 0) {
                                          alert("上传失败,请重试");
                                          return;
                                      } else if (responseText.Detail == "big") {
                                          var maxSize = accFile.parents("p[tp='p_uploadImg']").attr("maxSize");
                                          alert("文件大小不能超过" + maxSize + "KB");
                                          return;
                                      } else {
                                          var arrtext = responseText.Detail.split('|');
                                          accFile.prev().val(arrtext[0]);
                                          try {
                                              accFile.prevAll("input[name='PicPathList']").eq(0).val(arrtext[0]);
                                          } catch (e) { }
                                          accFile.prevAll("input[tp='hidden']").eq(0).val(arrtext[0]);
                                          accFile.prevAll("input[tp='hidden']").eq(0).valid && accFile.prevAll("input[tp='hidden']").eq(0).valid();
                                          accFile.prevAll("input[tp='hidden']").focus();
                                          accFile.prevAll("input[tp='hidden']").blur();
          
                                          accFile.prev().show();
          
                                          //判断是否是轮播图页面
                                          var node = accBtn.nextAll("input[tp=clearImg]").eq(0);
                                          if (node.length > 0) {
                                              accBtn.hide();
                                              accBtn.next().show(); //显示清除按钮
                                              accFile.hide();              //文件框隐藏
                                          }
                                          var img = accBtn.parent().find("img").eq(0);
                                          img.attr("displayImage", "True")
                                          if (img.attr("displayImage") == "True") {
                                              img.attr("src", arrtext[0]);
                                              img.show(); //显示照片
                                          }
                                          accFile.trigger("changecookiefile");
                                      }
                                  }
                              });
                          }
                      }
                      else {
                          //alert("请先选择要上传的图片!");
                      }
                  }
          	</script>

          里面有Ajax异步提交方法,具体见软件开发平台异步提交Ajax解析之ajaxSubmit

          我们从上面脚本可以看出,后台控制器和action为@Url.Action("Uploadfile", "UpLoadControl"),在action中获取文件信息后,通过远程网络传送到服务器,调用方法如下:

          string result = RemoteUploadFileNew(remoteUrl, FileServerUlr, filepath, userId, filePath, fileName);

          RemoteUploadFileNew方法实现如下:

          /// 上传本地图片到远程服务器
                  public static string RemoteUploadFileNew(string remoteUrl, string commonUrl, string specialPath, int userId, string filePath, string fileName = "")
                  {
                      string result = string.Empty;
                      FileStream fileStream = null;
                      Stream requestStream = null;
                      try
                      {
                          string param = "?userId=" + userId + "&filePath=" + specialPath + "&fileName=" + fileName;
                          remoteUrl += param;
                          string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
          
                          // Build up the post message header  
                          StringBuilder sb = new StringBuilder();
                          sb.Append("--");
                          sb.Append(boundary);
                          sb.Append("\r\n");
                          sb.Append("Content-Disposition: form-data; name=\"");
                          sb.Append(fileName);
                          sb.Append("\"; filename=\"");
                          sb.Append(Path.GetFileName(filePath));
                          sb.Append("\"");
                          sb.Append("\r\n");
                          sb.Append("Content-Type: ");
                          sb.Append("application/octet-stream");
                          sb.Append("\r\n");
                          sb.Append("\r\n");
          
                          string postHeader = sb.ToString();
                          byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
                          HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
          
                          webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
                          webrequest.Method = "POST";
                          webrequest.AllowWriteStreamBuffering = false;
                          byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
          
                          fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                          long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
                          webrequest.ContentLength = length;
          
                          requestStream = webrequest.GetRequestStream();
          
                          // Write out our post header  
                          requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
          
                          // Write out the file contents  
                          byte[] buffer = new byte[fileStream.Length];
                          int bytesRead = 0;
                          while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                              requestStream.Write(buffer, 0, bytesRead);
          
                          // Write out the trailing boundary  
                          requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
          
                          using (Stream response = webrequest.GetResponse().GetResponseStream())
                          {
                              using (StreamReader reader = new StreamReader(response))
                              {
                                  result = commonUrl + reader.ReadToEnd();
                              }
                          }
                      }
                      catch (WebException ex)
                      {
                          System.Diagnostics.Trace.WriteLine("图片上传失败," + ex.Message);
                          HttpWebResponse response = ex.Response as HttpWebResponse;
                          if (response != null)
                          {
                              throw new WebException();
                          }
                          throw new Exception();
                      }
                      catch (Exception exception)
                      {
                          System.Diagnostics.Trace.WriteLine("图片上传失败," + exception.Message);
                          throw new Exception();
                      }
                      finally
                      {
                          requestStream.Dispose();
                          if (fileStream != null) fileStream.Dispose();
                          if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath); // 删除压缩过后的图片
                      }
                      return result;
                  }

          可以看出我们先将文件读到内存,然后分字节端传输到远程服务器,远程服务器上的接受程序做逆向操作,并保存文件到硬盘。

          软件开发平台下载

          网站&系统开发技术学习交流群:463167176

          本站文章除注明转载外,均为本站原创或翻译,欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,共创和谐网络环境。
          转载请注明:文章转载自:软件开发框架 ? 软件开发平台文件上传下载
          本文标题:软件开发平台文件上传下载
          本文地址:http://www.sajuice.com/OrgTec/UI/0023.html

          相关文章: 软件开发平台Excel操作之NPOI方法

          电话
          电话 18718672256

          扫一扫
          二维码
          本港台开奖 <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <蜘蛛词>| <文本链> <文本链> <文本链> <文本链> <文本链> <文本链>