簡體   English   中英

在asp.net core中上傳文件

[英]Upload file in asp.net core

我是asp.net核心開發的新手,有人可以建議我如何管理和上傳我的根/文件文件夾中的文件。

您可以使用Request.Form.Files從您的請求中獲取文件。

    [HttpPost]
    [Route("api/v1/doaitems/upload/{id:int}")]
    public async Task<IActionResult> UploadFile(int id, [FromQuery] string distId, [FromQuery] string activity)
    {
        try
        {
            var file = Request.Form.Files[0];
            string folderName = "Uploads";
            string webRootPath = _env.WebRootPath;
            string newPath = Path.Combine(webRootPath, folderName);

            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file.Length > 0)
            {
                int MaxContentLength = 1024 * 1024 * 2; //2 MB
                string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf", ".xls", ".xlsx", ".doc", ".docx" };


                if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                {
                    ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                    TempData["UploadFail"] = "Failed";
                    return RedirectToAction("failed", "failed");
                }

                else if (file.Length > MaxContentLength)
                {
                    ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                    ViewBag.Message = "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB";
                    TempData["UploadFail"] = "Failed";
                    TempData["UploadSuccess"] = null;
                    return RedirectToAction("failed", "failed");
                }

                string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                string fullPath = Path.Combine(newPath, fileName);
                string filenameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
                string ext = Path.GetExtension(fullPath);
                fileName = filenameWithoutExtension + "_" + DateTime.Now.ToString("MM-dd-yy") + ext;
                fullPath = Path.Combine(newPath, fileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);

                    DocItem item = new DocItem
                    {
                        Name = fileName,
                        Description = fileName,
                        FileName = fileName,
                        FilePath = fullPath,
                        FileUri = folderName + "/" + fileName
                    };

                    await _dbContext.DocItems.AddAsync(item);

                    await _dbContext.SaveChangesAsync();

                }
            }

            return Json("Upload Successful.");
        }
        catch (Exception ex)
        {
            return Json("Upload Failed: " + ex.Message);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM