DotNetCore 微服务上传附件

后台接口升级成netcore 2.0了,然后之前的上传图片的接口就不再使用了。新的接口形式

#region IFormCollection
/// <summary>
/// IFormCollection
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
[HttpPost("UploadFiles")]
public IActionResult UploadFiles(IFormCollection files)
{
    try
    {
        var Files = Request.Form.Files;
        long size = Files.Sum(f => f.Length);
        //size > 100MB refuse upload !
        if (size > 104857600)
        {
            return Json(ResponseHelper.Error_Msg_Ecode_Elevel_HttpCode("files total size > 100MB , server refused !"));
        }

        List<string> filePathResultList = new List<string>();
        foreach (var file in Files)
        {
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            string filePath = hostingEnv.WebRootPath + @"\" + "Files" + @"\files\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            fileName = DateTime.Now.ToString("yyMMddHHmmss") + "_" + Guid.NewGuid() + "." + fileName.Split('.')[1];
            string fileFullName = filePath + fileName;
            using (FileStream fs = System.IO.File.Create(fileFullName))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            filePathResultList.Add($"/src/files/{fileName}");
        }
        string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!";
        return Json(ResponseHelper.IsSuccess_Msg_Data_HttpCode(message, filePathResultList, filePathResultList.Count));

    }
    catch (Exception ex)
    {
        return null;
    }
}
#endregion

那么前台文件传输也有不同方式,包括

1) 前端读取文件内容,将内容以text/xml/json/binary等形式传输。

2)前端不做任何处理,将文件放到Form中传输

我们来说说第二种方式

页面是随便的只要是H5相关的即可

@Html.HiddenFor(model => model.Photo)
<img class="expic" src="/Content/Images/NotPic.jpg" /><br />
<a href="javascript:$('#FileUpload').trigger('click');" class="files">@Resource.Browse</a>
<input type="file" class="displaynone" id="FileUpload" name="FileUpload" onchange="UploadFileCenter('FileUpload','Photo');" />
<span class="uploading">@Resource.Uploading</span>

页面中保证有这个input type=file的即可,然后调用相应的js,传入指定的参数,第一个是这个file的id,第二个是要保存的隐藏字段,其中有个回显的动作,在js里处理了,找那个和input file同级别的img标签进行回显

js代码如下

function UploadFileCenter(fileInput, fileHidden) {
    var url = Constants.globalPicUrl + "/api/FileUpload/UploadFiles";
    var fileUpload = $("#" + fileInput).get(0);
    var files = fileUpload.files;
    var formData = new FormData();
    for (var i = 0; i < files.length; i++) {
        formData.append(files[i].name, files[i]);
    }
    $.ajax({
        type: "POST",
        url: url,
        contentType: false,
        processData: false,
        data: formData,
        success: function (data) {
            if (data.code == 200) {
                $("#" + fileHidden).val(data.data[0]);
                $("#" + fileInput).siblings("img").attr("src", Constants.globalPicUrl + data.data[0]);
            } else {
                $.messageBox5s('@Resource.Tip', data.message);
            }
        },
        error: function () {
            $.messageBox5s('@Resource.Tip', "上传文件出现错误");
        }
    });
}

其实文件上传就可以直接用最简单的form提交即可。

posted @ 2018-10-31 11:10  Rexcnblog  阅读(681)  评论(0编辑  收藏  举报