c#上传文件并将word pdf转化成txt存储并将内容写入数据库

c#上传文件并将word pdf转化成txt存储并将内容写入数据库

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Office.Core;//添加引用 com Microsoft.Office 12.0
using Microsoft.Office.Interop.PowerPoint;//添加引用 com Microsoft Powerpoint 12.0 using Microsoft.Office.Interop.Word; //添加引用 com Microsoft word 12.0
using System.IO;
using org.pdfbox.util;//网上下载PDFBox-0.7.3 引用PDFBox-0.7.3.dll、IKVM.GNU.Classpath.dll、IKVM.Runtime.dll、FontBox-0.1.0-dev.dll
using org.pdfbox.pdmodel;
using System.Text;
public partial class _Default : System.Web.UI.Page
{dbcommand db = new dbcommand();prompt pt = new prompt();protected void Page_Load(object sender, EventArgs e){if (IsPostBack)return;}protected void decide_Click(object sender, EventArgs e){//获取文件全名string filename = fj.PostedFile.FileName.ToString();//上传文件类型string filetype = filename.Substring(filename.LastIndexOf('.') + 1);if (filetype == "doc" || filetype == "docx" || filetype == "pdf"){string strpath = "~/Upload/" + filename;fj.PostedFile.SaveAs(Server.MapPath(strpath));//获取文件名string strname = filename.Substring(0, filename.LastIndexOf('.')); FileInfo fi1 = new FileInfo(@"E:\FUL\Upload\" + filename);FileInfo fi2 = new FileInfo(@"E:\FUL\txt\" + strname + ".txt");if (filetype == "pdf")pdf2txt(fi1, fi2);elseword2text(fi1, fi2);StreamReader sr=text2reader(fi2);string sql="insert into fujian(subject,content) values('"+subject.Text+"','"+sr.ReadToEnd()+"')";int num=db.AffectedRow(sql);//写入数据库,返回影响行数函数,这里你可以自己写 if (num > 0)pt.message("上传成功!");//弹出对话框,这里你可以自己写
        }}/// <summary>/// pdf文件转成txt/// </summary>/// <param name="file"></param>/// <param name="txtfile"></param>public void pdf2txt(FileInfo file, FileInfo txtfile){PDDocument doc = PDDocument.load(file.FullName);PDFTextStripper pdfStripper = new PDFTextStripper();string text = pdfStripper.getText(doc);StreamWriter swPdfChange = new StreamWriter(txtfile.FullName, false,Encoding.GetEncoding("gb2312"));swPdfChange.Write(text);swPdfChange.Close();}/// <summary>///word文档转成txt,对于doc文件中的表格,读出的结果是去除掉了网格线,内容按行读取。 /// </summary>/// <param name="file"></param>/// <param name="txtfile"></param>public void word2text(FileInfo file, FileInfo txtfile){object readOnly = true;object missing = System.Reflection.Missing.Value;object fileName = file.FullName;Microsoft.Office.Interop.Word.ApplicationClass wordapp = newMicrosoft.Office.Interop.Word.ApplicationClass();Document doc = wordapp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);string text = doc.Content.Text;doc.Close(ref missing, ref missing, ref missing);wordapp.Quit(ref missing, ref missing, ref missing);StreamWriter swWordChange = new StreamWriter(txtfile.FullName, false,Encoding.GetEncoding("gb2312"));swWordChange.Write(text);swWordChange.Close();}public void ppt2txt(FileInfo file, FileInfo txtfile){Microsoft.Office.Interop.PowerPoint.Application pa = newMicrosoft.Office.Interop.PowerPoint.ApplicationClass();Microsoft.Office.Interop.PowerPoint.Presentation pp =pa.Presentations.Open(file.FullName,Microsoft.Office.Core.MsoTriState.msoTrue,Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoFalse);string pps = "";StreamWriter swPPtChange = new StreamWriter(txtfile.FullName, false,Encoding.GetEncoding("gb2312"));foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in pp.Slides){foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)pps += shape.TextFrame.TextRange.Text.ToString();}swPPtChange.Write(pps);swPPtChange.Close();}/// <summary>/// 取txt文件的内容/// </summary>/// <param name="file"></param>/// <returns></returns>public StreamReader text2reader(FileInfo file){StreamReader st = null;switch (file.Extension.ToLower()){case ".txt":st = new StreamReader(file.FullName, Encoding.GetEncoding("gb2312")); break;case ".doc":FileInfo wordfile = new FileInfo(@"E:\myprograms\200807program\FileSearch\App_Data\word2txt.txt");//不能使用相对路径,想办法改进 word2text(file, wordfile);st = new StreamReader(wordfile.FullName, Encoding.GetEncoding("gb2312")); break;case ".pdf":FileInfo pdffile = new FileInfo(@"E:\myprograms\200807program\FileSearch\App_Data\pdf2txt.txt");pdf2txt(file, pdffile);st = new StreamReader(pdffile.FullName, Encoding.GetEncoding("gb2312")); break;case ".ppt":FileInfo pptfile = new FileInfo(@"E:\myprograms\200807program\FileSearch\App_Data\ppt2txt.txt");ppt2txt(file, pptfile);st = new StreamReader(pptfile.FullName, Encoding.GetEncoding("gb2312")); break;}st = new StreamReader(file.FullName, Encoding.GetEncoding("gb2312"));return st;}}

//下面的和上面的没有直接关系,下面的只是上传文件
上传附件
<asp:FileUpload ID="FileUpload1" runat="server" />

 1 using System;
 2 using System.Data;
 3 using System.Configuration;
 4 using System.Web;
 5 using System.Web.Security;
 6 using System.Web.UI;
 7 using System.Web.UI.WebControls;
 8 using System.Web.UI.WebControls.WebParts;
 9 using System.Web.UI.HtmlControls;
10 public partial class _Default : System.Web.UI.Page
11 {
12     protected void Page_Load(object sender, EventArgs e)
13     {
14     }
15     protected void Button1_Click(object sender, EventArgs e)
16     {
17         string name = FileUpload1.FileName;//上传文件名
18         string size = FileUpload1.PostedFile.ContentLength.ToString();//得到上传文件的大小
19         string type = FileUpload1.PostedFile.ContentType;//得上传文件的类型
20         string type2 = name.Substring(name.LastIndexOf(".")+1);//得后缀名
21         string ipath = Server.MapPath("upimg") + "\\" + name;
22         if (FileType == "pdf" || FileType == "doc" || FileType == "xls" || FileType == "txt" || FileType == "jpg" || FileType == "JPG" || FileType == "gif" || FileType == "bmp" || FileType == "rar" || FileType == "zip" || FileType == "dwg")
23         {
24             FileUpload1.SaveAs("ipath");
25             Image1.ImageUrl = wpath;
26             Label1.Text = "上传文件的名称" + name + "上传文件的大小" + size + "上传文件的类型" + type + "后缀名" + type2 + "实际路径" + ipath;
27         }
28     }
29 }

打开附件:
前台:<asp:HyperLink ID="fj" runat="server" Visible="False"></asp:HyperLink>

 1 using System;
 2 using System.Data;
 3 using System.Configuration;
 4 using System.Collections;
 5 using System.Web;
 6 using System.Web.Security;
 7 using System.Web.UI;
 8 using System.Web.UI.WebControls;
 9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11 public partial class ViewBlog : System.Web.UI.Page
12 {
13     dbcommand db = new dbcommand();
14     prompt pt = new prompt();
15     protected void Page_Load(object sender, EventArgs e)
16     {
17         if (Session["username"] == null)
18         {
19             Response.Write("<script type='text/javascript'>alert('" + "请先登录!" + "');top.location='Login.aspx';</script>");
20             Response.End();
21         }
22         int id = int.Parse(HttpContext.Current.Request.QueryString["id"].ToString());
23         string sql = "select T_USER.username,T_Blog.* from T_USER,T_Blog where T_USER.id=T_Blog.blogUser and T_Blog.id=" + id;
24         DataSet ds = db.GetDateset(sql);
25         以下是显示附件信息
26         if (ds.Tables[0].Rows[0]["FileName"].ToString() != "")//如果有附件
27         {
28             fj.Text = ds.Tables[0].Rows[0]["FileName"].ToString();//显示附件名称
29             fj.Visible = true;
30             fj.NavigateUrl = "Upload/" + ds.Tables[0].Rows[0]["FileName"].ToString();//附件所在路径
31             fj.Target = "_blank";
32         }
33     }
34 }

FileUpload默认最大上传4m 要上传更大 可是web.config中设置 代码如下:

 1 <?xml version="1.0"?>
 2 <!--
 3 注意: 除了手动编辑此文件以外,您还可以使用
 4 Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
 5 “网站”->“Asp.Net 配置”选项。
 6 设置和注释的完整列表在
 7 machine.config.comments 中,该文件通常位于
 8 \Windows\Microsoft.Net\Framework\v2.x\Config 中
 9 -->
10 <configuration>
11 <appSettings/>
12 <connectionStrings>
13 <!--连接数据库 这里是sql server2008-->
14 <add name="strcnn" connectionString="Data Source=.;Initial Catalog=inshineProject;Persist Security Info=True;User ID=sa;Password=sa;Pooling=False" providerName="System.Data.SqlClient"/> </connectionStrings>
15 <system.web>
16 <!--
17 设置 compilation debug="true" 将调试符号插入
18 已编译的页面中。但由于这会
19 影响性能,因此只在开发过程中将此值
20 设置为 true。
21 -->
22 <!--这里调车最多可上传200M ,可以根据自己的需要设置更大-->
23 <httpRuntime executionTimeout="10000 " maxRequestLength="2048000 "/>
24 <compilation debug="true">
25 <assemblies>
26 <add assembly="System.Design, Version=2.0.0.0, Culture=neutral,PublicKeyToken=B03F5F7F11D50A3A"/>
27 <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
28 <!--
29 通过 <authentication> 节可以配置 ASP.NET 使用的
30 安全身份验证模式,
31 以标识传入的用户。
32 -->
33 <authentication mode="Windows"/>
34 <!--
35 如果在执行请求的过程中出现未处理的错误,
36 则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
37 开发人员通过该节可以配置
38 要显示的 html 错误页
39 以代替错误堆栈跟踪。
40 <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" />
41 <error statusCode="404" redirect="FileNotFound.htm" />
42 </customErrors>
43 -->
44 </system.web>
45 </configuration>

posted on 2016-10-08 14:50 明净 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/mingjing/p/5938732.html

c#上传文件并将word pdf转化成txt存储并将内容写入数据库相关推荐

  1. vue实战--vue+elementUI实现多文件上传+预览(word/PDF/图片/docx/doc/xlxs/txt)

    需求 最近在做vue2.0+element UI的项目中遇到了一个需求:需求是多个文件上传的同时实现文件的在线预览功能.需求图如下: 看到这个需求的时候,小栗脑袋一炸.并不知道该如何下手,之前的实践项 ...

  2. 微信小程序上传文件(图片/word等)功能)

    说到上传文件,首先要想到微信官方文档给的API,wx.uploadFile({ }) 通过这个API来达到上传至服务器的效果:代码示例如下 接下来我们先来说说上传图片功能,这个比较简单一些 上传图片: ...

  3. 微信小程序实现上传文件 如图片/word excel到服务器

    说道上传文件,首先要想到微信官方文档给的API,wx.uploadFile({ }) 通过这个API来达到上传至服务器的效果:代码示例如下 接下来我们先来说说上传图片功能,这个比较简单一些 上传图片: ...

  4. Java上传文件到数据库

    Java上传文件到数据库 首先在开始本文之前推荐一篇我非常喜欢的博主--孤傲苍狼的一篇相关博文. JavaWeb学习总结(五十)--文件上传和下载 http://www.cnblogs.com/xdp ...

  5. http 协议上传文件multipart form-data boundary 说明--转载

    原文地址:http://xixinfei.iteye.com/blog/2002017 含义 ENCTYPE="multipart/form-data" 说明:  通过 http ...

  6. php实现上传文件功能,简单实现php上传文件功能

    本文实例为大家分享了php上传文件功能的具体代码,供大家参考,具体内容如下 html: 文件名: php: // 允许上传的图片后缀 $allowedExts = array("gif&qu ...

  7. Spring Boot(十七):使用Spring Boot上传文件

    Spring Boot(十七):使用Spring Boot上传文件 环境:Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0 一.pom包配置 <parent> ...

  8. (转)Spring Boot(十七):使用 Spring Boot 上传文件

    http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html 上传文件是互联网中常常应用的场景之一,最典型的情 ...

  9. springboot上传文件同时传参数_Spring Boot 系列:使用 Spring Boot 上传文件

    上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 Spring Boot 上传文件的小案例. 1.pom 包配置 我们使用 Spring Boot 版本 2. ...

最新文章

  1. X-UA-Compatible也无法解决的IE11兼容问题
  2. html表单输入框添加验证码,织梦Dedecms为自定义表单添加验证码功能
  3. 导致定时器失效_IIS进程回收导致定时器失效的解决方法(CMD命令)
  4. 用户控件的后台代码关联使用CodeBehind还是CodeFile
  5. 李宏毅线性代数笔记9:特征值与特征向量
  6. 关于Verilog的可综合性
  7. Android之用adb screencap -p命令截图
  8. java队列优先级_优先级队列-Java的PriorityQueue与最小堆有何不同?
  9. 《软件测试》 第三次博客作业
  10. mysql 提交修改_MySQL客户端、服务器端工具、sql_mode、存储引擎修改、事务的提交和回滚、隔离级别...
  11. win10 安装 face_recognition
  12. 【语音分析】基于matlab短时自相关基音周期检测+LPC预测增益计算【含Matlab源码 1517期】
  13. [产品] 敏捷开发软件(一)——团队看板
  14. 基于Springboot+Vue+ElementUI物流配送管理系统
  15. Excel 精选28个技巧
  16. linux crw权限,linux中crw brw lrw等等文件属性是什么
  17. python ORM 模块peewee(三): Model的建立
  18. OSChina 周二乱弹 —— 好好告别啊!不要舌吻!
  19. OpenFOAM 张量运算
  20. 「上帝粒子」发现10周年

热门文章

  1. 人工智能新目标——看懂视频
  2. 【CRH】列车通过曲线时,曲线半径、超高值与车速的关系
  3. 电网计算机面试专业题,国家电网计算机管理员面试经验|面试题 - 职朋职业圈...
  4. 微型计算机最大的电路板是,微型计算机系统中最大的一块电路板被称作 。
  5. 基于SSM+Shiro+Redis+Layui的后台管理系统
  6. 【免费赠送源码】Springboot剧本杀交流分享平台1p7vg计算机毕业设计-课程设计-期末作业-毕设程序代做
  7. i.MXU6LL - 制作烧录SD卡详细步骤
  8. ANSYS的宏文件mac的创建和应用
  9. postfix各类故障详细分析与解决
  10. win10锁定计算机后黑屏,win10锁定屏幕就黑屏怎么办