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('.') + );
if (filetype == "doc" || filetype == "docx" || filetype == "pdf")
{
string strpath = "~/Upload/" + filename;
fj.PostedFile.SaveAs(Server.MapPath(strpath));
//获取文件名
string strname = filename.Substring(, 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);
else
word2text(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 = new
Microsoft.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 = new
Microsoft.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" />

 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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string name = FileUpload1.FileName;//上传文件名
string size = FileUpload1.PostedFile.ContentLength.ToString();//得到上传文件的大小
string type = FileUpload1.PostedFile.ContentType;//得上传文件的类型
string type2 = name.Substring(name.LastIndexOf(".")+);//得后缀名
string ipath = Server.MapPath("upimg") + "\\" + name;
if (FileType == "pdf" || FileType == "doc" || FileType == "xls" || FileType == "txt" || FileType == "jpg" || FileType == "JPG" || FileType == "gif" || FileType == "bmp" || FileType == "rar" || FileType == "zip" || FileType == "dwg")
{
FileUpload1.SaveAs("ipath");
Image1.ImageUrl = wpath;
Label1.Text = "上传文件的名称" + name + "上传文件的大小" + size + "上传文件的类型" + type + "后缀名" + type2 + "实际路径" + ipath;
}
}
}

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

 using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
public partial class ViewBlog : System.Web.UI.Page
{
dbcommand db = new dbcommand();
prompt pt = new prompt();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Response.Write("<script type='text/javascript'>alert('" + "请先登录!" + "');top.location='Login.aspx';</script>");
Response.End();
}
int id = int.Parse(HttpContext.Current.Request.QueryString["id"].ToString());
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;
DataSet ds = db.GetDateset(sql);
以下是显示附件信息
if (ds.Tables[].Rows[]["FileName"].ToString() != "")//如果有附件
{
fj.Text = ds.Tables[].Rows[]["FileName"].ToString();//显示附件名称
fj.Visible = true;
fj.NavigateUrl = "Upload/" + ds.Tables[].Rows[]["FileName"].ToString();//附件所在路径
fj.Target = "_blank";
}
}
}

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

 <?xml version="1.0"?>
<!--
注意: 除了手动编辑此文件以外,您还可以使用
Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
“网站”->“Asp.Net 配置”选项。
设置和注释的完整列表在
machine.config.comments 中,该文件通常位于
\Windows\Microsoft.Net\Framework\v2.x\Config 中
-->
<configuration>
<appSettings/>
<connectionStrings>
<!--连接数据库 这里是sql server2008-->
<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>
<system.web>
<!--
设置 compilation debug="true" 将调试符号插入
已编译的页面中。但由于这会
影响性能,因此只在开发过程中将此值
设置为 true。
-->
<!--这里调车最多可上传200M ,可以根据自己的需要设置更大-->
<httpRuntime executionTimeout="10000 " maxRequestLength="2048000 "/>
<compilation debug="true">
<assemblies>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral,PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
<!--
通过 <authentication> 节可以配置 ASP.NET 使用的
安全身份验证模式,
以标识传入的用户。
-->
<authentication mode="Windows"/>
<!--
如果在执行请求的过程中出现未处理的错误,
则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
开发人员通过该节可以配置
要显示的 html 错误页
以代替错误堆栈跟踪。
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>

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

  1. 关于js异步上传文件

    好久没登录博客园了,今天来一发分享. 最近项目里有个需求,上传文件(好吧,这种需求很常见,这也不是第一次遇到了).当时第一想法就是直接用form表单提交(原谅我以前就是这么干的),不过表单里不仅有文件 ...

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

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

  3. hadoopmaster主机上传文件出错: put: File /a.txt._COPYING_ could only be replicated to 0 nodes instead of minReplication (=1). There are 3 datanode(s) running and 3 node(s) are excluded in this operation.

    刚开始装好hadoop的时候,namenode机上传文件没有错误,今天打开时突然不能上传文件,报错 put: File /a.txt._COPYING_ could only be replicate ...

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

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

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

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

  6. spring boot(十七)上传文件

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

  7. 数据採集之Web端上传文件到Hadoop HDFS

    前言 近期在公司接到一个任务.是关于数据採集方面的. 需求主要有3个: 通过web端上传文件到HDFS; 通过日志採集的方式导入到HDFS; 将数据库DB的表数据导入到HDFS. 正好近期都有在这方面 ...

  8. C# FileStream进行FTP服务上传文件和下载文件

    定义FileStream类的操作类:操作类名: FtpUpDown 上传文件 /// <summary> /// 上传文件 /// </summary> /// <par ...

  9. HDFS基本命令行操作及上传文件的简单API

    一.HDFS基本命令行操作: 1.HDFS集群修改SecondaryNameNode位置到hd09-2 (1)修改hdfs-site.xml <configuration> //配置元数据 ...

随机推荐

  1. Vim NerdTree

    参考链接:http://yang3wei.github.io/blog/2013/01/29/nerdtree-kuai-jie-jian-ji-lu/ 切换工作台和目录 ctrl + w + h 光 ...

  2. go bytes缓冲区使用介绍 -转自https://www.cnblogs.com/--xiaoyao--/p/5122138.html

    缓冲区原理简介: go字节缓冲区底层以字节切片做存储,切片存在长度len与容量cap, 缓冲区写从长度len的位置开始写,当len>cap时,会自动扩容.缓冲区读会从内置标记off位置开始读(o ...

  3. 自定义Write节点的afterrender属性

    由于nuke中的write节点提供了beforerender,afterrender这类事件,我们想添加一些功能只需要在这里面敲入代码即可.事件一旦发生,自然会触发我们敲入的co de.   Nuke ...

  4. C# 调用Sql server 执行存储过程总是返回-1

    调用存储过程代码如下: 今天在写存储过程调用时遇到如下问题: int value = cmd.ExecuteNonQuery();//执行总是返回-1:且存储过程在sql 可视化执行窗口可正常执行-- ...

  5. 【mongodb】之安装

    export PATH=/opt/mongodb64-3.4.10/bin:$PATHmongod --dbpath data --logpath logs/mongo.log --fork

  6. 《剑指offer(第二版)》面试题55——判断是否为平衡二叉树

    一.题目大意 输入一颗二叉树,判断该二叉树是否为平衡二叉树(AVL树). 二.题解 <剑指offer>上给出了两种解决方式: 1.第一种是从根节点开始,从上往下遍历每个子节点并计算以子节点 ...

  7. Ansible基础入门

    1.1 Ansible是什么        随着移动互联.物联网.互联网+.大数据.云计算等大规模应用的催生推动,以及人们日常生活的互联网化,互联网的蓬勃发展不仅冲击影响着整个经济体,更对人们的生活理 ...

  8. [UE4]GameMode、GameInstance、GameState、PlayerState、PlayerController

    一.只有PlayerController和Pawn/Character才有输入事件(键盘.鼠标等等),PlayerState没有输入事件. 二.对于需要跨域关卡的数据信息,根据上图所知需要放到Game ...

  9. [UE4]运行时进入观察模式

  10. Go语言 数据类型,流程控制

    Go语言 数据类型,流程控制 人生苦短,Let's Go ! package main // 必须要有一个main包 import "fmt" func main() { fmt. ...