随笔 - 89  文章 - 0  评论 - 2  阅读 - 11万 

接到一个需求,需要将图片及其他数据信息存储到txt文件下并根据上传时间分别打包到文件夹内。

需要打包的数据:Img1,img2,updatetime,carcode,address

分析:首先,创建一级文件夹:firstFile,创建二级文件夹:secondFile.

           其次,将carcode,address数据存储到txt文本内

           第三,将txt文本和img1、img2分别存储到secondFile文件夹

           第四,压缩文件并下载

           第五,删除压缩包及创建的文件夹

结果:程序根目录下的Download文件夹内,

     

 

 

代码:

 

1
2
3
4
5
6
7
8
9
10
11
<strong>创建一级文件夹FirstFile</strong>
  
public string FirstCreate(string dt)
        {
            string path = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download/记录_" + dt;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
<strong>创建二级文件夹 secondFile</strong>
 
public string SecondCreate(string path,string vdt, string CarNo)
        {
            string dt = DateTime.Now.ToString("yyyyMMddHHmmss");
            vdt = DateTime.Parse(vdt).ToString("yyyyMMddHHmmss");
            string filname = path + "\\" + vdt + "_" + CarNo;
            if (!Directory.Exists(filname))
            {
                Directory.CreateDirectory(filname);
            }
            return filname;
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<strong>将数据存入到txt文件中</strong>
 
        public bool txtData(string path, string bianhao, string carcode, string carcolor, string cartype, string codecolor, string violationtime, string violationaddr, string x, string y)
        {
            string filename = path + "\\" + carcode + ".txt";//这是地址
            string Text = "编号:" + bianhao + "\r\n" +"车辆牌号:" + carcode + "\r\n" +"地点:" + violationaddr ;
            FileStream fs = new FileStream(filename, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
            sw.Write(Text);
            sw.Close();
            fs.Close();
            return true;
        }<br>
<strong>图片在数据库中存储的未URL,所以需要根据图片地址下载图片到本地磁盘<br><br></strong>
        /// <summary>
        /// 从图片地址下载图片到本地磁盘
        /// </summary>
        /// <param name="ToLocalPath">图片本地磁盘地址</param>
        /// <param name="Url">图片网址</param>
        /// <returns></returns>
        public bool SavePhotoFromUrl(string FileName, string Url)
        {
            bool Value = false;
            WebResponse response = null;
            Stream stream = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                response = request.GetResponse();
                stream = response.GetResponseStream();
 
                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    Value = SaveBinaryFile(response, FileName);
                }
                //stream.Close();
                 
            }
            catch (Exception err)
            {
                string aa = err.ToString();
            }
            return Value;
        }
        /// <summary>
        /// Save a binary file to disk.
        /// </summary>
        /// <param name="response">The response used to save the file</param>
        // 将二进制文件保存到磁盘
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];
            try
            {
                //if (File.Exists(FileName))
                //    File.Delete(FileName);
                //Stream outStream = System.IO.File.Create(FileName+"\\"+ carcode+".jpg");
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();
 
                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);
 
                //outStream.Flush();
                outStream.Close();
                //inStream.Flush();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<strong>压缩文件<br>此处需要引用:</strong>/// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="sourceFilePath">待拷贝文件或文件夹 绝对路径</param>
        /// <param name="destinationZipFilePath"> 生成zip文件的绝对路径 </param>
        public void CreateZip(string sourceFilePath, string destinationZipFilePath)
        {
            if (sourceFilePath[sourceFilePath.Length - 1] != Path.DirectorySeparatorChar)
                sourceFilePath += Path.DirectorySeparatorChar;
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
            zipStream.SetLevel(6);  // 压缩级别 0-9
            CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);
 
            zipStream.Finish();
            zipStream.Close();
        }
 
        /// <summary>
        /// 递归压缩文件
        /// </summary>
        /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
        /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>
        /// <param name="staticFile"></param>
        public void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
        {
            if (sourceFilePath[sourceFilePath.Length - 1] != Path.DirectorySeparatorChar)
                sourceFilePath += Path.DirectorySeparatorChar;
            Crc32 crc = new Crc32();
            string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
            foreach (string file in filesArray)
            {
                if (Directory.Exists(file))                     //如果当前是文件夹,递归
                {
                    CreateZipFiles(file, zipStream, staticFile);
                }
                else//如果是文件,开始压缩
                {
                    FileStream fileStream = File.OpenRead(file);
 
                    byte[] buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, buffer.Length);
                    string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1);
                    ZipEntry entry = new ZipEntry(tempFile);
 
                    entry.DateTime = DateTime.Now;
                    entry.Size = fileStream.Length;
                    fileStream.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    zipStream.PutNextEntry(entry);
 
                    zipStream.Write(buffer, 0, buffer.Length);
                    //zipStream.Flush();
                    //zipStream.Close();
 
                }
            }
        }

using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<strong>下载文件(在控制器中写)</strong>
 
public void OutPutZipFile(HttpContext context, string fileName)
        {
            //客户端保存的文件名
            string zipname = fileName;
            //目标文件路径
            string filePath = Server.MapPath("~/Download/" + fileName + "");
            //Console.WriteLine(filePath);
            FileInfo fileInfo = new FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();// "attachment;filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(name))
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(zipname)));
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Range", "bytes 0-" + (fileInfo.Length - 1) + "/" + fileInfo.Length);
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = Encoding.GetEncoding("gb2312");
            Response.Flush();
            //文件发送到客户端
            Response.WriteFile(fileInfo.FullName);
            Response.End();
            Response.Close();
            //string zipName = "违法停车.zip";
            //string filePath = Server.MapPath("~/Download/" + fileName + "");
            ////string filePath = Base_Dir + "\\" + fileName;
            //FileStream fs = new FileStream(filePath, FileMode.Open);//使用字节流的方式打开
            //byte[] bytes = new byte[(int)fs.Length];
            //fs.Read(bytes, 0, bytes.Length);
            //fs.Close();
            //Response.ContentType = "application/octet-stream";
            //Response.AddHeader("Title", fileName);
            ////通知浏览器下载文件而不是打开
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipName, System.Text.Encoding.UTF8));
            //Response.BinaryWrite(bytes);
            //Response.Flush();
            //Response.End();
        }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<strong> 删除文件,此处有些麻烦,会有更好的解决方式</strong>
<br>//删除文件夹
        public void DelectDir(string srcPath)
        {
            if (File.Exists(srcPath))
            {
                // 2、根据路径字符串判断是文件还是文件夹
                FileAttributes attr = File.GetAttributes(srcPath);
                // 3、根据具体类型进行删除
                if (attr == FileAttributes.Directory)
                {
                    // 3.1、删除文件夹
                    Directory.Delete(srcPath, true);
                }
                else
                {
                    // 3.2、删除文件
                    File.Delete(srcPath);
                }
                File.Delete(srcPath);
            }
        }
 
        //删除download文件夹下的所有子文件,删除zip文件
        public void DeleteDir(string file)
        {
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                DirectoryInfo fileInfo = new DirectoryInfo(file);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
 
                //去除文件的只读属性
                File.SetAttributes(file, FileAttributes.Normal);
 
                //判断文件夹是否还存在
                if (Directory.Exists(file))
                {
                    foreach (string f in Directory.GetFileSystemEntries(file))
                    {
                        if (File.Exists(f))
                        {
                            //如果有子文件删除文件
                            File.Delete(f);
                            Console.WriteLine(f);
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            DeleteDir(f);
                        }
                    }
                    //删除空文件夹
                    Directory.Delete(file);
                }
            }
            catch (Exception ex) // 异常处理
            {
                Console.WriteLine(ex.Message.ToString());// 异常信息
            }
        }

  

1
代码调用获取需要打包的数据DataTable table = new DataTable();string str="select img1,img2,carcode,address,updatetime from table";table = this.BaseRepository().FindTable(str.ToString());//创建一级菜单,目录为~Download/记录_202107300902 string dt = DateTime.Now.ToString("yyyyMMddHHmmss"); string firstPath = df.FirstCreate(dt);foreach (DataRow dr in table.Rows){   string carcode = dr["carcode"].ToString();   string carcode = dr["address"].ToString();   string carcode = dr["img1"].ToString();   string carcode = dr["img2"].ToString();   //创建二级菜单,并将url地址图片存放到二级菜单中} 

using System.Data;
using System.Text;
using System.IO;

using System.Text;

using System.Web;

        string TheFolder = df.SecondCreate(firstPath, updatetime, carcode);
        //图片地址
        string Img1 = TheFolder + "\\" + carcode + "_1.jpg";
        string Img2 = TheFolder + "\\" + carcode + "_2.jpg";
        //图片下载到子文件夹中
        SavePhotoFromUrl(Img1, img1Url);
        SavePhotoFromUrl(Img2, img2Url);

        //将其他数据存储到txt文件中

         txtData(TheFolder,carcode,address,updatetime);

//待压缩的文件或文件夹路径路径+文件名称
string ZipFilePath = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download /记录_" + FirstFileName + ".zip";
CreateZip(firstPath, ZipFilePath);

//下载文件

this.OutPutZipFile(Request.RequestContext.HttpContext.ApplicationInstance.Context, zipName);//调用方式

//删除文件

string destFilePath = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download/记录_" + FirstFileName ;
DeleteDir(destFilePath);
string Path = @System.AppDomain.CurrentDomain.BaseDirectory + @"Download/记录_" + FirstFileName + ".zip";
DelectDir(Path);

 

       注意: 

 1、添加引用CSharpCode.SharpZipLib.dll ,此处引用的版本为:0.85.4.369。

      引用0.85.4.369版本的dll从服务器上下载解压没有问题,但是添加了0.86.0.518版本,从服务器上下载下来后解压提示图片文件头损坏。【此处巨坑。。。。。。】

添加引用的方式(vs2017):

工具——NuGet包管理器——管理解决方案的NuGet程序包

 

 

2、添加后,运行代码,可能会报出【未能加载文件或程序集“ICSharpCode.SharpZipLib”或它的某一个依赖项】这种错误,

 

 

     解决方式:将ICSharpCode.SharpZipLib.dll 复制到web下的bin下面即可。

 

posted on   我的梦想是开个小店  阅读(1620)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示