码迷,mamicode.com
首页 > Web开发 > 详细

阿里云附件文件流的形式上传、下载

时间:2017-12-13 11:36:09      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:tom   ntb   附件文件   method   for   验证   bre   efault   warning   

 

1、View附件上传

 

@using (Html.BeginForm("StartUpLoad", "ReferenceDocument", new {id = ViewBag.Id}, FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<input type="file" name="filedata" id="fileUpLoad"class="btn btn-success"/><br/>
<input type="submit" value="提交" id="submitFile" class="btn btn-success"/>
<span id="warning" style="color: red; font-size: large;"></span>
}

 

<script>
var fileTypeBool;
var fileSizeBool;
var file = getNameFromPath($("#fileUpLoad").val());
if (file == null) {
$("#submitFile").attr("disabled", true);
}

//判断文件大小
function GetFileSize(fileid) {
var fileSize = 0;
fileSize = $("#" + fileid)[0].files[0].size;
fileSize = fileSize / 1048576;
return fileSize;
}

//根据路径得到文件名
function getNameFromPath(strFilepath) {
var objRe = new RegExp(/([^\/\\]+)$/);
var strName = objRe.exec(strFilepath);

if (strName == null) {
return null;
} else {
return strName[0];
}
}

//当更换文件时触发Change事件对其文件类型和文件大小进行验证:
$("#fileUpLoad").change(function() {
var file = getNameFromPath($(this).val());

if (file != null) {
var errors = $(document).find(".field-validation-error");
$.each(errors,
function(k, v) {
if ($(v).attr("data-valmsg-for") === "fileUpLoad") {
$(v).hide();
}
});
var extension = file.substr((file.lastIndexOf(‘.‘) + 1));
switch (extension) {
case ‘pdf‘:
fileTypeBool = false;
break;
default:
fileTypeBool = true;
}
}
if (fileTypeBool) {
$("#warning").html("只能上传扩展名为pdf的文件!");
$("#submitFile").attr("disabled", true);
return false;
} else {
var size = GetFileSize(‘fileUpLoad‘);
if (size > 10) {
fileSizeBool = true;
$("#warning").html("上传文件已经超过10兆!");
$("#submitFile").attr("disabled", true);
} else {
fileSizeBool = false;
$("#submitFile").attr("disabled", false);
$("#warning").html("");
}
}
return false;
});

$("#submitFile").submit(function () {
var file = getNameFromPath($(this).val());

alert(fileTypeBool);
alert(fileSizeBool);
if (fileTypeBool || fileSizeBool) {
return false;
}
$("input[type=‘text‘]").each(function(k, v) {
if ($(v).length) {
$(v).siblings("span").hide();
}
});
return false;
});
</script>

2、控制器处理文件流

/// <summary>
/// 1、创建Oss服务实例
/// </summary>
/// <returns></returns>
private static OssClient CreatOssClient()
{
return new OssClient(Config.OssConfig.EndpointUri, Config.OssConfig.AccessKeyId,
Config.OssConfig.AccessKeySecret);
}

/// <summary>
////2、pdf附件上传
/// </summary>
/// <param name="id">唯一标识</param>
/// <param name="filedata"></param>
/// <returns></returns>
[CustomAuthorize]
[HttpPost]
public ActionResult StartUpLoad(long id, HttpPostedFileBase filedata)
{
try
{
#region 判断文件大小、类型

const int maxContentLength = 1024 * 1024 * 10;
if (string.IsNullOrEmpty(filedata?.FileName) || filedata.ContentLength == 0)
{
return HttpNotFound("附件不存在");
}
if (filedata.ContentLength > maxContentLength)
{
throw new Exception($"上传图片过大,不能超过{maxContentLength / 1024}兆");
}
if (!filedata.ContentType.Equals("application/pdf"))
{
throw new Exception("只能上传pdf文件");
}
var user = LoginFactory.GetCurrentLoginUser();
if (user == null) throw new ArgumentException("当前用户未登录");
var fileOssSaveName = $"{Guid.NewGuid().ToString()}.pdf";
var fielSqlSaveName = filedata.FileName;

#endregion

#region 保存文件到阿里云OSS

#region 初始化OSS实例

var bucketName = Config.OssConfig.ClimsBucketName;
var ossClient = CreatOssClient();

#endregion

if (!ossClient.DoesBucketExist(bucketName))
{
throw new ArgumentException($"阿里云存储空间{bucketName}不存在");
}

#region 判断Oss是否存在模拟文件夹(文件名/)

const string folderName = "refdocfiles"; //存储文件的文件夹(refdocfiles/
if (!ossClient.DoesObjectExist(bucketName, folderName + "/"))
{
using (var stream = new MemoryStream(new byte[0]))
{
ossClient.PutObject(bucketName, folderName + "/", stream);
}
}

#endregion

#region 使用inputStream上传文件

var metadata = new ObjectMetadata
{
ContentEncoding = "utf-8",
ContentType = "application/pdf"
};
var bytes = new byte[filedata.ContentLength];
filedata.InputStream.Read(bytes, 0, bytes.Length);
var putObject = ossClient.PutObject(bucketName, folderName + "/" + fileOssSaveName,
new ByteArrayInputStream(bytes), metadata);

#endregion

#endregion

#endregion

#region 附件上传信息保存数据库

var document = new ReferenceDocument()
{
Id = id,
FileName = fielSqlSaveName,
FilePath = folderName + $"/{fileOssSaveName}", //相对路径
UpLoadUserId = user.UserId,
UpLoadTime = DateTime.Now
};
RequestHelper.PostT("api/UploadRecord", document);

#endregion

return Content("<script>alert(‘技术依据附件上传成功!‘);window.open(‘" +
Url.Content(@"/ReferenceDocument/Index") +
"‘, ‘_self‘);</script>");
}
catch (Exception e)
{
Console.WriteLine(e);
throw new Exception(e.Message);
}
}


#region 附件下载

/// <summary>
/// 附件下载
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[CustomAuthorize]
public FileResult DownFile(long id)
{
try
{
var user = LoginFactory.GetCurrentLoginUser();
if (user == null)
{
throw new ArgumentException("当前用户未登录");
}
var refDoc = ReferenceDocumentBll.Retrieve(id);
if (refDoc == null)
{
throw new ArgumentException("未找到依据");
}

#region 初始化OSSClient实例

var bucketName = Config.OssConfig.ClimsBucketName;
var ossClient = CreatOssClient();
if (!ossClient.DoesObjectExist(bucketName, refDoc.FilePath))
{
throw new ArgumentException("附件不存在");
}

#endregion

#region 文件读取

var fileObject = ossClient.GetObject(bucketName, refDoc.FilePath);
return File(fileObject.Content, "application/octet-stream",
HttpUtility.UrlEncode(refDoc.FileName, Encoding.UTF8));

#endregion
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}

#endregion

阿里云附件文件流的形式上传、下载

标签:tom   ntb   附件文件   method   for   验证   bre   efault   warning   

原文地址:http://www.cnblogs.com/william-CuiCui0705/p/8031288.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!