文件读取,保存操作

大体需求:读取指定文件->进行相关处理->新建文件并保存内容【用户选择后缀名“.mlc”文件后再把得到的".flc"文件保存到相关路径下】

解决方案:1、根据用户选择的‘.mlc’文件先上传到服务器端;

     2、从服务器端取出该文件用文件流进行读取操作;

       3、经过处理的文件以‘.flc’后缀保存到服务器端 ;

              4、最后弹出下载框供用户下载保存。

第二种解决方案是使用ActiveX,之前的一篇《BS实现文件夹上传下载_终结篇》可以参考下。

前台代码:

 1 <div>
 2         <input type="hidden" id="hdFilePaht" runat="server" />
 3         <%--这里建立一个隐藏域 用来存地址--%>
 4         <table style=" 100%;" id="mytable" cellspacing="0">
 5             <tr>
 6                 <td align="center">
 7                     离线激活
 8                 </td>
 9             </tr>
10             <tr>
11                 <td align="center">
12                     <asp:FileUpload ID="fpLoad" onchange="CheckFileType()" runat="server" />
13                 </td>
14             </tr>
15             <tr>
16                 <td align="center">
17                     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="请选择上传文件!"
18                         ControlToValidate="fpLoad"></asp:RequiredFieldValidator>
19                     <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="仅允许上传mlc文件!"
20                         ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(mlc)$" ControlToValidate="fpLoad" />
21                 </td>
22             </tr>
23             <tr>
24                 <td align="center">
25                     <asp:Button ID="btnActive" runat="server" Text="激 活" Enabled="False" OnClientClick="return checkNull()"
26                         OnClick="btnActive_Click" />
27                     &nbsp; &nbsp;
28                     <asp:Button ID="btnCancel" runat="server" Text="取 消" />
29                 </td>
30             </tr>
31         </table>
32     </div>

js

  FileUpload获取上传文件的路径,有说设置浏览器安全,但是毕竟不是可取的方法。这里我只限IE其实也不是很好的方法

 1         function CheckFileType() {
 2             if (!document.all) {
 3                 alert("请使用IE浏览器");
 4                 return;
 5             }
 6             var objButton = document.getElementById("btnActive"); //激活按钮
 7             var objFileUpload = document.getElementById('fpLoad'); //FileUpload 
 8             var FileName = new String(objFileUpload.value); //文件名
 9             var extension = new String(FileName.substring(FileName.lastIndexOf(".") + 1, FileName.length)); //文件扩展名 
10             if (extension == "mlc" || extension == "MLC") 
11             {
12                 objButton.disabled = false; //启用上传按钮 
13             }
14             else {
15                 objButton.disabled = true; //禁用上传按钮
16                 alert('仅允许上传mlc文件!'); 
17             }
18         }

后台代码:

  /// <summary>
        /// 激活    
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnActive_Click(object sender, EventArgs e)
        {
            if (fpLoad.HasFile)
            {
                try
                {
                    string filePath = hdFilePaht.Value;//文件路径   
                    string fileExt = System.IO.Path.GetExtension(fpLoad.FileName);
                    if (fileExt != ".mlc")
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('仅限mlc文件');</script>");
                        return;
                    }
                    string savePath = Server.MapPath("/mlcFile");//文件上传路径
                    if (!Directory.Exists(savePath))
                        Directory.CreateDirectory(savePath);
                    string fileSavePath = savePath + "\\" + DateTime.Now.ToString("yyyyMMddhhmmssfff") + "_" + fpLoad.FileName;
                    if (File.Exists(fileSavePath))
                        File.Delete(fileSavePath); //文件上传存在则删除
                    fpLoad.SaveAs(fileSavePath);
                    byte[] btRead = FileToBinary(fileSavePath);
                    string read = System.Text.Encoding.ASCII.GetString(btRead);
                    …………………………
            ………………………………
一些数据处理(可不管)
…………………………
byte[] byDataValue = System.Text.Encoding.ASCII.GetBytes(encrypt); string fileOutPath = savePath + "\\" + fpLoad.FileName.Split('.')[0] + ".flc"; if (File.Exists(fileOutPath)) File.Delete(fileOutPath); //转换后文件存在则删除 BinaryToFile(savePath, fpLoad.FileName.Split('.')[0] + ".flc", byDataValue); Response.Redirect("http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/mlcFile/" + fpLoad.FileName.Split('.')[0] + ".flc"); } catch (Exception ex) { ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('发生错误:" + ex.Message.ToString() + "');</script>"); } } else ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择上传文件');</script>"); } #region FoldHelper /// <summary>将文件转换为二进制流进行读取 /// </summary> /// <param name="fileName">文件完整名路径</param> /// <returns>文件二进制流</returns> private static byte[] FileToBinary(string fileName) { FileStream fsRead = new FileStream(fileName, FileMode.Open, FileAccess.Read); try { if (fsRead.CanRead) { int fsSize = Convert.ToInt32(fsRead.Length); byte[] btRead = new byte[fsSize]; fsRead.Read(btRead, 0, fsSize); return btRead; } else { throw new Exception("文件读取错误!"); } } catch (Exception ex) { throw new Exception(ex.Message); } finally { fsRead.Close(); } } /// <summary> 将二进制流转换为对应的文件进行存储 </summary> /// <param name="storePath">存储文件名的路径</param> /// <param name="fileName">文件名</param> /// <param name="btBinary">二进制流</param> private static void BinaryToFile(string storePath, string fileName, byte[] binary) { FileStream fsWrite = new FileStream(storePath + "\\" + fileName, FileMode.Create, FileAccess.Write); try { if (fsWrite.CanWrite) { fsWrite.Write(binary, 0, binary.Length); } } catch (Exception ex) { throw new Exception(ex.Message); } finally { fsWrite.Close(); } } #endregion

效果图:一

效果图:二

注意:效果是出来了,但不是我们要的下载页面的效果,这里还有注意如果后缀是‘.flc’ ……浏览器解析不了则显示不存在该文件 。不是不存在是浏览器它不认识。所以要进行一些设置。如下:

效果图:三: IIS设置 如果你要下载其他格式的文件,则添加进去就可以了

效果图:四 

效果图:五 保存后效果

                                                   


作者:PEPE
出处:http://pepe.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。


作者:PEPE
出处:http://pepe.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/PEPE/p/2440456.html