Unity本地图片文件上传服务器(或者数据库),并从服务器(或者数据库)下载+图片生成PDF并保存到数据库+SQLite数据库增删改查

avatar
作者
猴君
阅读量:1

@TOC

一、前言

最近博主用以前的小功能总是搬来扒去,感觉。。。
正好汇总一下,以后再用直接扒博客,下面是博主整理的一些功能点:sqlite数据库(包含增删改查),本地图片上传下载(数据库或者服务器),图片生成pdf(插入表格、标题等等),pdf上传数据库并下载等。。。。。。最后附上项目源码,希望对广大网友有所帮助。

二、插件附上(源码中获得即可)

  1. iTextSharp.dll
  2. LitJson.dll
  3. sqlite3.dll
  4. system.data.dll
  5. pdfrenderAPI
  6. BestHttp
  7. RestClient

相关插件

相关插件

三、创建PDF,打印PDF

1.导入iTextSharp插件后,在项目中新建一个场景,创建一个按钮和一个脚本TestReport.cs(随便挂在一个物体上即可);并给按钮绑定创建pdf事件,下方是全部代码。

using System; using System.Collections; using UnityEngine; using UnityEngine.UI;  public class TestReport : MonoBehaviour {     public Button button;     private AndroidJavaClass unityPlayerClass;     private AndroidJavaObject unityActivity;     private AndroidJavaObject alert;     string path = Application.streamingAssetsPath + "/test.pdf";      void Start()     {         button.onClick.AddListener(() => { StartCoroutine(CreatPDF()); });     }      #region 创建pdf      /// <summary>     /// 创建PDF     /// </summary>     /// <returns></returns>     public IEnumerator CreatPDF()     {         using (PDFReport pdf = new PDFReport())         {             yield return pdf.Init(path);             pdf.AddTitle("我是测试报告标题",1);//这是标题             pdf.AddNullLine();//添加空白行             pdf.AddContent("姓名:测试者           证件号:000000000000000000");             pdf.AddNullLine();             pdf.AddContent("测试项目:项目一        测试时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm"));             pdf.AddNullLine();             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot1.jpg");             pdf.AddNullLine();             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot2.jpg");             pdf.AddNullLine();             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot3.jpg");         }          Debug.Log("创建成功打开文件:" + path);         Application.OpenURL(path);             }      #endregion     } 

项目场景如图所示:
创建按钮,添加脚本
运行场景如下,可直接连接打印机打印pdf:
生成的pdf文件
注解:主要脚本PDFReport.cs脚本里包含了生成pdf的基础设置:字体、样式、标题、添加表格、空行、文本内容、图片等。

using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using UnityEngine; using UnityEngine.Networking; using Font = iTextSharp.text.Font; using Image = iTextSharp.text.Image;  public class PDFReport : IDisposable {     /// <summary>     /// 基础字体     /// </summary>     BaseFont heiBaseFont;      /// <summary>     /// 报告字体样式     /// </summary>     public Font titleFont;      /// <summary>     /// 大标题字体样式     /// </summary>     public Font firstTitleFont;      /// <summary>     /// 小标题字体样式     /// </summary>     public Font secondTitleFont;      /// <summary>     /// 内容字体样式     /// </summary>     public Font contentFont;      /// <summary>     /// 文档     /// </summary>     public Document document;      /// <summary>     /// 字体在安卓中的路径     /// </summary>     string newFontPath;      /// <summary>     /// 拷贝资源到读写路径     /// </summary>     /// <param name="Oldpath"></param>     /// <param name="newPath"></param>     /// <returns></returns>     public static IEnumerator CopyOldPathToNewPath(string Oldpath, string newPath)     {         if (File.Exists(newPath))         {             yield break;         }          Uri uri = new Uri(Oldpath);         using (UnityWebRequest request = UnityWebRequest.Get(uri))         {             yield return request.SendWebRequest();             if (string.IsNullOrEmpty(request.error))             {                 yield return File.WriteAllBytesAsync(newPath, request.downloadHandler.data);             }             else             {                 Debug.LogError(request.error);             }         }     }      /// <summary>     /// 初始化     /// </summary>     /// <param name="filePath"></param>     /// <returns></returns>     public IEnumerator Init(string filePath)     {         document = new Document(PageSize.A4);         string dirPath = Path.GetDirectoryName(filePath);         Directory.CreateDirectory(dirPath);         FileStream os = new FileStream(filePath, FileMode.Create);         PdfWriter.GetInstance(document, os);         document.Open();                  Debug.LogError(document.PageNumber);                  string oldPath = Application.streamingAssetsPath + "/SourceHanSansSC-Medium.otf";         newFontPath = Application.persistentDataPath + "/SourceHanSansSC-Medium.otf";         yield return CopyOldPathToNewPath(oldPath, newFontPath);         //创建字体         heiBaseFont = BaseFont.CreateFont(newFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);         titleFont = new Font(heiBaseFont, 26, 1);         firstTitleFont = new Font(heiBaseFont, 20, 1);         secondTitleFont = new Font(heiBaseFont, 13, 1);         contentFont = new Font(heiBaseFont, 11, Font.NORMAL);     }      /// <summary>     /// 添加pdf表格     /// </summary>     /// <param name="dt"></param>     public void AddDataTable(DataTable dt)     {         List<float> columns = new List<float>();         for (int i = 0; i < dt.Columns.Count; i++)         {             columns.Add(1);         }          AddDataTable(dt, columns.ToArray());     }      /// <summary>     /// 添加pdf表格     /// </summary>     /// <param name="dt"></param>     /// <param name="columnW">列</param>     public void AddDataTable(DataTable dt, float[] columnW)     {         List<string> list = new List<string>();         for (int i = 0; i < dt.Columns.Count; i++)         {             string s = dt.Columns[i].ColumnName;             list.Add(s);         }          //数据 行         foreach (DataRow row in dt.Rows)         {             for (int i = 0; i < dt.Columns.Count; i++)             {                 string s = row[i].ToString();                 list.Add(s);             }         }          AddTable(columnW, list.ToArray());     }      /// <summary>     /// 增加表格     /// </summary>     /// <param name="column">列数宽度比例</param>     /// <param name="content">内容</param>     public void AddTable(float[] columns, string[] content)     {         PdfPTable table = new PdfPTable(columns);         table.WidthPercentage = 100;         //table.SetTotalWidth(new float[] {10,10,10,10,10,10,10,20 });         for (int i = 0; i < content.Length; i++)         {             PdfPCell cell = new PdfPCell(new Phrase(content[i], contentFont));             cell.HorizontalAlignment = Element.ALIGN_CENTER;             cell.VerticalAlignment = Element.ALIGN_MIDDLE;              table.AddCell(cell);         }          document.Add(table);     }       /// <summary>     /// 空格     /// 加入空行,用以区分上下行     /// </summary>     public void AddNullLine()     {         Paragraph nullLine = new Paragraph(" ", secondTitleFont);         nullLine.Leading = 5;         document.Add(nullLine);     }      /// <summary>     /// 加入标题     /// </summary>     /// <param name="titleStr">标题内容</param>     /// <param name="font">标题字体,分为一级标题和二级标题</param>     /// <param name="alignmentType">对齐格式,0为左对齐,1为居中</param>     public void AddTitle(string titleStr, int alignmentType = 0)     {         Paragraph contentP = new Paragraph(new Chunk(titleStr, titleFont));         contentP.Alignment = alignmentType;         document.Add(contentP);     }      /// <summary>     /// 插入文字内容     /// </summary>     /// <param name="content">内容</param>     /// <param name="alignmentType">对齐格式,0为左对齐,1为居中</param>     public void AddContent(string content, int alignmentType = 0)     {         Paragraph contentP = new Paragraph(new Chunk(content, contentFont));         contentP.Alignment = alignmentType;         document.Add(contentP);     }           /// <summary>     /// 插入图片     /// </summary>     /// <param name="imagePath"></param>     /// <param name="scale"></param>     public void AddImage(string imagePath)     {         if (!File.Exists(imagePath))         {             Debug.LogWarning("该路径下不存在指定图片,请检测路径是否正确!");             return;         }         iTextSharp.text.Document Doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);         Rectangle defaultPageSize = iTextSharp.text.PageSize.A4;         // float pageWidth = defaultPageSize.Width - Doc.RightMargin - Doc.LeftMargin;//留白         // float pageHeight = defaultPageSize.Height - Doc.TopMargin - Doc.BottomMargin;                  Image image = Image.GetInstance(imagePath);         image.ScaleToFit(defaultPageSize.Width,defaultPageSize.Height);         image.Alignment = Element.ALIGN_JUSTIFIED;         document.Add(image);     }      /// <summary>     /// 关闭文档     /// </summary>     public void Dispose()     {         document.Close();     } } 

四、创建sqlite数据库,截取屏幕图片生成PDF,并将PDF并保存至数据库

1.新建一个场景,创建脚本SQLiteManager.cs,挂在一个空物体上
2.在StreamingAssets文件夹里创建UseTable.db数据库
3.SQLiteStudio下载安装步骤:这位博主写的很详细,请参考安装即可
[https://blog.csdn.net/m0_37149062/article/details/135138080]
4.部分原理:
1.在UseTable.db中创建表行和列,如下图所示,脚本DbAccess.cs里包含了数据库的增删改查
在这里插入图片描述
代码部分:

using UnityEngine; using System; using System.Collections; using Mono.Data.Sqlite;  namespace Imdork.SQLite {     /// <summary>     /// SQLite数据库操作类     /// </summary>     public class DbAccess : IDisposable     {         private SqliteConnection conn; // SQLite连接         private SqliteCommand cmd; // SQLite命令         private SqliteDataReader reader;          /// <summary>         /// 打开数据库         /// </summary>         /// <param name="connectionString"></param>         public DbAccess(string connectionString)         {             OpenDB(connectionString);         }          public DbAccess()         {         }          /// <summary>         /// 打开数据库         /// </summary>         /// <param name="connectionString"></param>         public void OpenDB(string connectionString)         {             Debug.Log(connectionString);             try             {                 conn = new SqliteConnection(connectionString);                 conn.Open();                 Debug.Log("Connected to db,连接数据库成功!");             }             catch (Exception e)             {                 string temp1 = e.ToString();                 Debug.Log("接连库据数败失:" + temp1);             }         }          /// <summary>         /// 关闭数据库连接         /// </summary>         public void CloseSqlConnection()         {             if (cmd != null)             {                 cmd.Dispose();                 cmd = null;             }              if (reader != null)             {                 reader.Dispose();                 reader = null;             }              if (conn != null)             {                 conn.Close();                 conn = null;             }              Debug.Log("Disconnected from db.关闭数据库!");         }          /// <summary>         /// 回收资源         /// </summary>         public void Dispose()         {             CloseSqlConnection();         }          /// <summary>         /// 执行SQL语句 用于Update/Insert/Delete         /// </summary>         /// <param name="sqlQuery"></param>         /// <returns></returns>         public int ExecuteNonQuery(string sqlQuery)         {             Debug.Log("ExecuteNonQuery:: " + sqlQuery);             cmd = conn.CreateCommand();             cmd.CommandText = sqlQuery;             int rows = cmd.ExecuteNonQuery();             return rows;         }           #region 更新数据          /// <summary>         /// 更新数据 param tableName=表名  cols=更新字段 colsvalues=更新内容         /// </summary>         /// <param name="tableName"></param>         /// <param name="selectKeys"></param>         /// <param name="selectValues"></param>         /// <param name="cols"></param>         /// <param name="colsValues"></param>         /// <returns></returns>         public int UpdateIntoSpecific(string tableName, string[] cols, string[] colsValues)         {             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";             }              return ExecuteNonQuery(query);         }          /// <summary>         /// 更新数据 param tableName=表名  selectkey=查找字段(主键) selectvalue=查找内容 cols=更新字段 colsvalues=更新内容         /// </summary>         /// <param name="tableName"></param>         /// <param name="selectKeys"></param>         /// <param name="selectValues"></param>         /// <param name="cols"></param>         /// <param name="colsValues"></param>         /// <returns></returns>         public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] selectValues, string[] cols,             string[] colsValues)         {             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";             }              query += " WHERE " + selectKeys[0] + " = " + "'" + selectValues[0] + "' ";             for (int i = 1; i < selectKeys.Length; ++i)             {                 query += " AND " + selectKeys[i] + " = " + "'" + selectValues[i] + "' ";             }              return ExecuteNonQuery(query);         }          /// <summary>         /// 更新数据 param tableName=表名  selectkey=查找字段(主键) operation=判断的符号 selectvalue=查找内容 cols=更新字段 colsvalues=更新内容         /// </summary>         /// <param name="tableName"></param>         /// <param name="selectKeys"></param>         /// <param name="operation"></param>         /// <param name="selectValues"></param>         /// <param name="cols"></param>         /// <param name="colsValues"></param>         /// <returns></returns>         public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] operation, string[] selectValues,             string[] cols, string[] colsValues)         {             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";             }              query += " WHERE " + selectKeys[0] + " " + operation[0] + " " + "'" + selectValues[0] + "' ";             for (int i = 1; i < selectKeys.Length; ++i)             {                 query += " AND " + selectKeys[i] + " " + operation[i] + " " + "'" + selectValues[i] + "' ";             }              return ExecuteNonQuery(query);         }          #endregion          #region 插入数据          #region 插入部分数据          /// <summary>         /// 插入部分数据         /// </summary>         /// <param name="tableName">表名</param>         /// <param name="cols">字段名</param>         /// <param name="values">具体数值</param>         /// <returns></returns>         public int InsertIntoSpecific(string tableName, string[] cols, string[] values)         {             if (cols.Length != values.Length)             {                 throw new Exception("columns.Length != colType.Length");             }              string query = "INSERT INTO " + tableName + " (" + cols[0];             for (int i = 1; i < cols.Length; ++i)             {                 query += ", " + cols[i];             }              query += ") VALUES (" + "'" + values[0] + "'";             for (int i = 1; i < values.Length; ++i)             {                 query += ", " + "'" + values[i] + "'";             }              query += ")";             return ExecuteNonQuery(query);         }          #endregion          #region 插入一行数据          /// <summary>         /// 插入一行数据 param tableName=表名 values=插入数据内容         /// </summary>         public int InsertInto(string tableName, string[] values)         {             string query = "INSERT INTO " + tableName + " VALUES (" + string.Format("'{0}'", values[0]);             for (int i = 1; i < values.Length; ++i)             {                 query += ", " + string.Format("'{0}'", values[i]);             }              query += ")";             return ExecuteNonQuery(query);         }          #endregion          #endregion          #region 删除表          #region 根据条件删除表          /// <summary>         /// 删除         /// </summary>         /// <param name="tableName">表名</param>         /// <param name="cols">字段</param>         /// <param name="colsValues">字段值</param>         /// <returns></returns>         public int Delete(string tableName, string[] cols, string[] colsValues)         {             string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += " and " + cols[i] + " = " + "'" + colsValues[i] + "'";             }              return ExecuteNonQuery(query);         }          /// <summary>         /// 删除表         /// </summary>         /// <param name="tableName"></param>         /// <param name="cols"></param>         /// <param name="operation"></param>         /// <param name="colsValues"></param>         /// <returns></returns>         public int Delete(string tableName, string[] cols, string[] operation, string[] colsValues)         {             string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " " + operation[0] + " " + "'" +                            colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += " and " + cols[i] + " " + operation[i] + " " + "'" + colsValues[i] + "'";             }              return ExecuteNonQuery(query);         }          #endregion          /// <summary>          /// 删除表中全部数据         /// </summary>         public int DeleteContents(string tableName)         {             string query = "DELETE FROM " + tableName;             return ExecuteNonQuery(query);         }          #endregion          #region 创建表          /// <summary>         /// 创建表 param name=表名 col=字段名 colType=字段类型         /// </summary>         public int CreateTable(string name, string[] col, string[] colType)         {             if (col.Length != colType.Length)             {                 throw new SqliteException("columns.Length != colType.Length");             }              string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];             for (int i = 1; i < col.Length; ++i)             {                 query += ", " + col[i] + " " + colType[i];             }              query += ")";             return ExecuteNonQuery(query);         }          #endregion          #region 查询表          #region 按条件查询全部数据          /// <summary>         /// 按条件查询全部数据 param tableName=表名  col=查找字段 operation=运算符 values=内容         /// </summary>         public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] operation, string[] values)         {             if (col.Length != operation.Length || operation.Length != values.Length)             {                 throw new SqliteException("col.Length != operation.Length != values.Length");             }              string query = "SELECT *";              query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          /// <summary>         /// 按条件查询全部数据 param tableName=表名 col=查找字段  values=内容         /// </summary>         public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] values)         {             if (col.Length != values.Length)             {                 throw new SqliteException("col.Length != values.Length");             }              string query = "SELECT *";             query += " FROM " + tableName + " WHERE " + col[0] + "=" + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + "=" + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          #endregion          #region 按条件查询数据          /// <summary>         /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段 operation=运算符 values=内容         /// </summary>         public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] operation,             string[] values)         {             if (col.Length != operation.Length || operation.Length != values.Length)             {                 throw new SqliteException("col.Length != operation.Length != values.Length");             }              string query = "SELECT " + items[0];             for (int i = 1; i < items.Length; ++i)             {                 query += ", " + items[i];             }              query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          /// <summary>         /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段  values=内容         /// </summary>         public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] values)         {             if (col.Length != values.Length)             {                 throw new SqliteException("col.Length != values.Length");             }              string query = "SELECT " + items[0];             for (int i = 1; i < items.Length; ++i)             {                 query += ", " + items[i];             }              query += " FROM " + tableName + " WHERE " + col[0] + "=" + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + "=" + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          #endregion          #region 按条件查询 单个字段数据          /// <summary>         ///  查询表         /// </summary>         /// <param name="tableName">表名</param>         /// <param name="col">查找字段</param>         /// <param name="operation">运算符</param>         /// <param name="values">内容</param>         /// <returns></returns>         public SqliteDataReader Select(string tableName, string col, string operation, string values)         {             string query = "SELECT * FROM " + tableName + " WHERE " + col + " " + operation + " " +                            string.Format("'{0}'", values);             return ExecuteQuery(query);         }          /// <summary>         /// 查询表         /// </summary>         /// <param name="tableName">表名</param>         /// <param name="col">查找字段</param>         /// <param name="values">内容</param>         /// <returns></returns>         public SqliteDataReader Select(string tableName, string col, string values)         {             string query = "SELECT * FROM " + tableName + " WHERE " + col + " = " + string.Format("'{0}'", values);             return ExecuteQuery(query);         }          #endregion          #region 升序查询/降序查询/查询表行数/查询表全部数据          /// <summary>         /// 升序查询         /// </summary>         public SqliteDataReader SelectOrderASC(string tableName, string col)         {             string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " ASC";             return ExecuteQuery(query);         }          /// <summary>         /// 降序查询         /// </summary>         public SqliteDataReader SelectOrderDESC(string tableName, string col)         {             string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " DESC";             return ExecuteQuery(query);         }          /// <summary>         /// 查询表行数         /// </summary>         public SqliteDataReader SelectCount(string tableName)         {             string query = "SELECT COUNT(*) FROM " + tableName;             return ExecuteQuery(query);         }          /// <summary>         /// 查询表中全部数据 param tableName=表名          /// </summary>         public SqliteDataReader ReadFullTable(string tableName)         {             string query = "SELECT * FROM " + tableName;             return ExecuteQuery(query);         }          #endregion          /// <summary>         /// 执行SQL语句 用于SelectWhere查询语句         /// </summary>         /// <param name="sqlQuery"></param>         /// <returns></returns>         public SqliteDataReader ExecuteQuery(string sqlQuery)         {             Debug.Log("ExecuteQuery:: " + sqlQuery);             cmd = conn.CreateCommand();             cmd.CommandText = sqlQuery;             try             {                 reader = cmd.ExecuteReader();             }             catch (Exception e)             {                  Debug.LogError(e);                 return null;             }              return reader;         }          #endregion     } }  

2.屏幕截图,获取图片的base64字节流
在这里插入图片描述
3.将pdf文件转成base64字节流插入数据库
在这里插入图片描述
4.完整代码如下:

using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Cysharp.Threading.Tasks; using Imdork.SQLite; using Manager; using Tool; using UnityEngine; using UnityEngine.UI;  public class SQLiteManager : MonoSingleton<SQLiteManager> {     #region 数据基本设置      /// <summary>     /// 数据库名称     /// </summary>     [Header("数据库名称")] public string UseTableName = "UseTable";      /// <summary>     /// 数据库路径     /// </summary>     private string UseTablePath;      [HideInInspector] public List<DataBase> dataList;      /// <summary>     /// 打印层相机     /// </summary>     public Camera printCamera;      /// <summary>     /// 所有图片更新GO     /// </summary>     public List<GameObject> AllTables;      /// <summary>     /// 截图路径     /// </summary>     string _path = Application.streamingAssetsPath + "/PrintImage/Screenshot";      string pathPDF = Application.streamingAssetsPath + @"\test.pdf"; //要打印的目标图片      private List<string> allImagePath;      private Coroutine _CreatPDF;     private GameObject curGO;     Rect rect;     RenderTexture rt;      void Awake()     {         rect = new Rect(0, 0, 1920, 1080);         rt = new RenderTexture((int)rect.width, (int)rect.height, 0);         UseTablePath = "Data Source = " + Application.streamingAssetsPath + "/" + UseTableName;     }      public void Start()     {         for (int i = 0; i < AllTables.Count; i++)         {             AllTables[i].SetActive(false);         }          ToInsertData();     }      void ToInsertData()     {         DataBase curDataBase = new DataBase();         curDataBase.ProjectName = "我是测试项目";         curDataBase.UserName = "测试";         curDataBase.UserID = "000000000000000000";         curDataBase.Time = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm");         PrintImage(curDataBase);     }      /// <summary>     /// 读取配置文件  账号登录     /// </summary>     /// <param name="path"></param>     /// <param name="callBack"></param>     /// <returns></returns>     private bool ReadData(string path, Action<string> callBack)     {         if (!File.Exists(path))         {             return false;         }          var str = File.ReadAllText(path);         callBack?.Invoke(str);         return true;     }      #endregion      #region 用户信息表格      /// <summary>     /// 获取当前用户的所有信息     /// </summary>     public void GetAllUseData()     {         GetDB(db =>         {             var reader = db.ReadFullTable("UserData");              List<DataBase> _userDatas = SQLiteUtility.GetDataValues(reader);             dataList.Clear();             if (_userDatas != null)             {                 for (int i = 0; i < _userDatas.Count; i++)                 {                     if (_userDatas[i].UserID == "000000000000000000")                     {                         dataList.Add(_userDatas[i]);                     }                 }             }         });     }      /// <summary>     /// 插入当前患者数据     /// </summary>     /// <param name="curUserData"></param>     public void InsertUserData(DataBase curUserData)     {         GetDB(db =>         {             db.InsertInto("UserData", GetSingleUserData(curUserData));             if (_CreatPDF != null) StopCoroutine(_CreatPDF);         });     }      /// <summary>     /// 将单个userdata数据拼接成字符串  按照数据库表顺序     /// </summary>     /// <param name="curUserData"></param>     /// <returns></returns>     String[] GetSingleUserData(DataBase curUserData)     {         List<string> strList = new List<string>();          strList.Add(curUserData.UserName);         strList.Add(curUserData.UserID);         strList.Add(curUserData.ProjectName);         strList.Add(curUserData.Time);         strList.Add(curUserData.PrintImage);          return strList.ToArray();     }      #endregion       /// <summary>     /// 调用数据库     /// </summary>     /// <param name="action"></param>     public void GetDB(Action<DbAccess> action)     {         //Path数据库文件,一定是StreamingAssets文件夹下 填写的路径文件不需要填写.db后缀         //创建数据库读取类         SQLiteHelper helper = new SQLiteHelper(UseTablePath);         //打开数据库 存储数据库操作类         using (var db = helper.Open())         {             //调用数据库委托             action(db);         }         /*          因为每次使用数据 添/删/改/查 都需要使用完后Close掉          重复代码,写无数次太麻烦 因为数据库操作类 继承了IDisposable接口 所以,          using会自动关闭数据库连接,我们无需手动关闭数据库          */     }       private void OnDestroy()     {         GetDB(db => db.Dispose());     }      #region 截图  打印      /// <summary>     /// 截图     /// </summary>     public async void PrintImage(DataBase _dataBase)     {         Debug.LogError(_dataBase.ProjectName);         for (int i = 0; i < AllTables.Count; i++)         {             Debug.LogError(AllTables[i].name);             if (_dataBase.ProjectName.Contains(AllTables[i].name))             {                 AllTables[i].SetActive(true);                 curGO = AllTables[i];             }             else             {                 AllTables[i].SetActive(false);             }         }          allImagePath = new List<string>();         Debug.LogError(curGO.transform.childCount);         for (int i = 0; i < curGO.transform.childCount; i++)         {             allImagePath.Add(_path + i + ".png");             ScreenTool(_path + i + ".png");             await Task.Delay(500);             curGO.transform.GetChild(i).gameObject.SetActive(false);         }          _CreatPDF = StartCoroutine(CreatPDF(_dataBase));     }      /// <summary>     /// 截图     /// </summary>     /// <param name="path"></param>     async void ScreenTool(string path)     {         printCamera.targetTexture = rt;         printCamera.Render();         RenderTexture.active = rt;         Texture2D _screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false);         _screenShot.ReadPixels(rect, 0, 0);         _screenShot.Apply();         await UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate);         printCamera.targetTexture = null;         RenderTexture.active = null;         var bytes = _screenShot.EncodeToPNG();         await File.WriteAllBytesAsync(path, bytes);         Debug.LogError($"截屏了一张照片: {path}");     }      /// <summary>     /// 创建pdf     /// </summary>     /// <param name="_dataBase"></param>     /// <returns></returns>     public IEnumerator CreatPDF(DataBase _dataBase)     {         using (PDFReport pdf = new PDFReport())         {             yield return pdf.Init(pathPDF);             for (int i = 0; i < allImagePath.Count; i++)             {                 pdf.AddImage(allImagePath[i]);             }         }          yield return new WaitForSeconds(0.2f);         string strBase = System.Convert.ToBase64String(File.ReadAllBytes(pathPDF));         _dataBase.PrintImage = strBase;         InsertUserData(_dataBase);         Debug.Log("创建成功打开文件:" + pathPDF);     }      #endregion } 

五、将本地图片文件上传至服务器,服务器返回一个图片文件下载地址,通过下载地址下载对应的图片文件

注解:在这里需要一个后台服务器用来储存文件地址并返回下载地址,所以在此直接做成一个工具类,调用接口直接传服务器请求URL和本地文件路径:

using System; using System.IO; using System.Net; using System.Text; using UnityEngine;  public static class HttpTool {     /// <summary>     /// Http上传文件     /// </summary>     /// <param name="url">服务器地址</param>     /// <param name="path">文件路径</param>     /// <returns>服务器返回的文件下载地址</returns>     public static string HttpUploadFile(string url, string path)     {         HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;         CookieContainer cookieContainer = new CookieContainer();         request.CookieContainer = cookieContainer;         request.AllowAutoRedirect = true;         request.Method = "POST";         string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线         request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;         byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");         byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");         int pos = path.LastIndexOf("\\");         string fileName = path.Substring(pos + 1);          StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));         byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());          FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);         byte[] bArr = new byte[fs.Length];         fs.Read(bArr, 0, bArr.Length);         fs.Close();          Stream postStream = request.GetRequestStream();         postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);         postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);         postStream.Write(bArr, 0, bArr.Length);         postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);         postStream.Close();         HttpWebResponse response = request.GetResponse() as HttpWebResponse;         Stream instream = response.GetResponseStream();         StreamReader sr = new StreamReader(instream, Encoding.UTF8);         string content = sr.ReadToEnd();         DataShellStr _data = JsonUtility.FromJson<DataShellStr>(content);//这里需要序列化,获取后台返回的文件下载地址         Debug.Log(content);         return _data.data;     }      }  

PS:附带一个博主网络请求常用的方法:RestClient插件,请求失败2秒后继续请求
在这里插入图片描述

项目源码,包含相关插件和完整代码。希望能够帮到你,别忘记点赞+收藏哦,谢谢。。。

[百度网盘地址]
链接:https://pan.baidu.com/s/1-xcJEBgONxLhxenLnT95RQ
提取码:6666
–来自百度网盘超级会员V6的分享

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!