移动服务器文件上传,【分享】移动附件上传_6.X

using Kingdee.BOS.Core;

using Kingdee.BOS.Core.Metadata;

using Kingdee.BOS.FileServer.Core;

using Kingdee.BOS.FileServer.Core.Object;

using Kingdee.BOS.FileServer.ProxyService;

using Kingdee.BOS.KDThread;

using Kingdee.BOS.Mobile.Metadata.ControlDataEntity;

using Kingdee.BOS.Mobile.PlugIn;

using Kingdee.BOS.Mobile.PlugIn.ControlModel;

using Kingdee.BOS.Orm.DataEntity;

using Kingdee.BOS.ServiceHelper;

using Kingdee.BOS.Util;

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.Text;

using System.Web;

namespace Kingdee.BOS.Mobile.FormPlugIns.Test

{

///

/// 附件上传测试

///

///

/// 附件上传涉及以下步骤:

/// 1. 附件控件将选取文件拷贝到临时目录

/// 2. 触发AfterMobileUpload函数并传入所需参数

/// 3. 从临时目录将文件保存至数据库或文件服务器

///

[Description("测试附件上传")]

public class TestAccessoryUpload : AbstractMobilePlugin

{

///

/// 上传类型, 0为数据库,1为文件服务,2为亚马逊云,3为金蝶云

///

private int submitType = 0;

///

/// 按钮点击事件

///

///

public override void ButtonClick(Core.DynamicForm.PlugIn.Args.ButtonClickEventArgs e)

{

if ("FSubmit2DB".EqualsIgnoreCase(e.Key))

{

// 使用数据库进行附件存取

submitType = 0;

}

else if ("FSubmit2FileServer".EqualsIgnoreCase(e.Key))

{

// 采用文件服务器方式进行附件存取

// 检查是否启用了文件服务器

if (!Kingdee.BOS.ServiceHelper.FileServer.FileServerHelper.UsedFileServer(this.Context))

{

this.View.ShowMessage("未启用文件服务器,无法实现上传。");

return;

}

// 取Cloud服务器配置的存储方式进行附件存储

submitType = Kingdee.BOS.ServiceHelper.FileServer.FileServerHelper.GetFileStorgaeType(this.Context);

}

// 先将客户端附件上传至临时目录

this.View.GetControl("FFileUpdate").UploadFieldBatch();

base.ButtonClick(e);

}

///

/// 附件上传至本地临时目录后的回调函数

///

///

public override void AfterMobileUpload(PlugIn.Args.MobileUploadEventArgs e)

{

// 获取服务器临时目录

string tempDirPath = HttpContext.Current.Request.PhysicalApplicationPath + KeyConst.TEMPFILEPATH;

// 获取附件表的元数据类

var formMetadata = (FormMetadata)MetaDataServiceHelper.Load(this.Context, FormIdConst.BOS_Attachment);

List dynList = new List();

StringBuilder sb = new StringBuilder();

foreach (FiledUploadEntity file in e.FileNameArray)

{

// 检查文件是否成功上传到临时目录

if (!file.IsSuccess)

{

continue;

}

// 检查文件是否存在于临时目录

var fileName = System.IO.Path.Combine(tempDirPath, file.FileName);

if (!System.IO.File.Exists(fileName))

{

continue;

}

/**

* 此处几个关键属性解读:

* 1. BillType  关联的模型的FormId

* 2. BillNo    关联的单据编号,用于确定此附件是属于哪张单据

* 3. InterID   关联的单据/基础资料ID,附件列表就是根据这个ID进行加载

* 4. EntryInterID  关联的单据体ID,这里我们只演示单据头,所以固定设置为-1

* 5. AttachmentSize    系统统一按照KB单位进行显示,所以需要除以1024

* 6. FileStorage   文件存储类型,0为数据库,1为文件服务,2为亚马逊云,3为金蝶云

*/

var dataBuff = System.IO.File.ReadAllBytes(fileName);

var dyn = new DynamicObject(formMetadata.BusinessInfo.GetDynamicObjectType());

if (submitType != 0)

{

// 将数据上传至文件服务器,并返回上传结果

var result = this.UploadAttachment(file.FileName, dataBuff);

if (!result.Success)

{

// 上传失败,收集失败信息

sb.AppendLine(string.Format("附件:{0},上传失败:{1}", file.FileName, result.Message));

continue;

}

// 通过这个FileId就可以从文件服务器下载到对应的附件

dyn["FileId"] = result.FileId;

}

else

{

// 数据库的方式是直接保存附件数据

dyn["Attachment"] = dataBuff;

}

// 此处我们不绑定到特定的单据,为了简化示例,只实现单纯的文件上传与下载

dyn["BillType"] = "Test_MOB_Accessory"; // 虚拟FormId

dyn["BillNo"] = "A00001"; // 虚拟的单据编号

dyn["InterID"] = "D00001"; // 虚拟的InterId,这个ID将作为我们下载的识别标识

// 上传文件服务器成功后才加入列表

dyn["AttachmentName"] = file.FileName;

dyn["AttachmentSize"] = Math.Round(dataBuff.Length / 1024.0, 2);

dyn["EntryInterID"] = -1;// 参照属性解读

dyn["CreateMen_Id"] = Convert.ToInt32(this.Context.UserId);

dyn["CreateMen"] = GetUser(this.Context.UserId.ToString());

dyn["ModifyTime"] = dyn["CreateTime"] = TimeServiceHelper.GetSystemDateTime(this.Context);

dyn["ExtName"] = System.IO.Path.GetExtension(file.FileName);

dyn["FileStorage"] = submitType.ToString();

dynList.Add(dyn);

}

if (dynList.Count > 0)

{

// 所有数据加载完成后再一次性保存全部

BusinessDataServiceHelper.Save(this.Context, dynList.ToArray());

sb.AppendLine();

sb.AppendLine(string.Join(",", dynList.Select(dyn => dyn["AttachmentName"].ToString()).ToArray()) + ",上传成功");

}

this.Model.SetValue("FLog", sb.ToString());

base.AfterMobileUpload(e);

}

///

/// 上传附件方法

///

///

///

///

private FileUploadResult UploadAttachment(string fileName, byte[] dataBuff)

{

// 初始化上传下载服务,这个Service会根据Cloud配置自动上传到对应的文件服务器

var service = new UpDownloadService();

int len = 0, less = 0;

string fileId = null;

byte[] buff = null;

while (len < dataBuff.Length)

{

// 文件服务器采用分段上传,每次上传4096字节, 最后一次如果不够则上传剩余长度

less = (dataBuff.Length - len) >= 4096 ? 4096 : (dataBuff.Length - len);

buff = new byte[less];

Array.Copy(dataBuff, len, buff, 0, less);

len += less;

using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buff))

{

TFileInfo tFile = new TFileInfo()

{

FileId = fileId,

FileName = fileName,

CTX = this.Context,

Last = len >= dataBuff.Length,//标记是否为文件的最后一个片段

Stream = ms

};

var result = service.UploadAttachment(tFile);

// 注意点:上传时fileId传入null为新文件开始,会返回一个文件的fileId,后续采用这个fileId标识均为同一文件的不同片段。

fileId = result.FileId;

if (!result.Success)

{

return result;

}

}

}

return new FileUploadResult()

{

Success = true,

FileId = fileId

};

}

///

/// 获取用户

///

///

///

DynamicObject GetUser(string userID)

{

OQLFilter filter = OQLFilter.CreateHeadEntityFilter(string.Format("FUSERID={0}", userID));

return BusinessDataServiceHelper.Load(this.View.Context, FormIdConst.SEC_User, null, filter).FirstOrDefault();

}

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
上传文件可以使用 HTML 的 `<form>` 标签和 `<input>` 标签来实现。需要将 `<form>` 标签的 `enctype` 属性设置为 `multipart/form-data`,这样浏览器就会将表单中的文件数据进行特殊的编码,然后再将编码后的数据发送给服务器。在服务器端,可以使用 PHP 提供的 $_FILES 数组来获取上传的文件信息。 以下是一个简单的上传文件的 HTML 表单: ``` <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="上传文件" name="submit"> </form> ``` 其中,`action` 属性指定了表单提交的 URL,`method` 属性指定了表单提交的方法(此处为 POST),`enctype` 属性指定了表单数据的编码方式。`<input>` 标签的 `type` 属性为 `file`,表示这是一个文件上传的输入框,`name` 属性为 `fileToUpload`,表示上传文件的参数名。 在服务器端,可以使用以下 PHP 代码来处理上传的文件: ``` <?php if(isset($_POST["submit"])) { $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // 检查文件是否已存在 if (file_exists($target_file)) { echo "对不起,该文件已存在。"; $uploadOk = 0; } // 检查文件大小 if ($_FILES["fileToUpload"]["size"] > 500000) { echo "对不起,文件过大。"; $uploadOk = 0; } // 允许特定的文件格式 if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "对不起,只允许上传 JPG, JPEG, PNG 和 GIF 文件。"; $uploadOk = 0; } // 检查 $uploadOk 是否为 0 if ($uploadOk == 0) { echo "对不起,文件上传失败。"; // 如果一切都没问题,尝试上传文件 } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "文件 ". basename( $_FILES["fileToUpload"]["name"]). " 上传成功。"; } else { echo "对不起,文件上传失败。"; } } } ?> ``` 代码中首先检查了上传文件的大小、格式等信息,如果有问题则提示用户上传失败。如果一切都没问题,则将上传的文件移动到指定的目录中。 文件下载可以使用 PHP 的 `readfile()` 函数来实现。以下是一个简单的下载文件的 PHP 代码: ``` <?php $file = "example.txt"; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); readfile($file); exit; } else { echo "对不起,文件不存在。"; } ?> ``` 代码中首先检查了要下载的文件是否存在,如果存在则设置了 HTTP 响应头,告诉浏览器该文件需要以附件形式下载。最后调用了 `readfile()` 函数将文件内容输出到客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值