【发布时间】:2021-10-26 06:52:18
【问题描述】:
我对 c# 和 ASP.NET 非常陌生,到目前为止,一位朋友帮助我完成了我的作业。作业包括我上传和下载文件的站点(到一个称为上传的文件夹和站点)。我想要一个删除文件的功能。任何人都可以根据我的代码给我代码吗?非常感谢,我不知道该怎么做。
using FileUploadDownload.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using TestAuth.Models;
using Aspose;
using Microsoft.Office.Interop.Word;
using ceTe.DynamicPDF.Conversion;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocToPDFConverter;
using Syncfusion.Pdf;
using Syncfusion.DocIO;
using Leadtools;
using Leadtools.Codecs;
using Leadtools.Document.Converter;
using Leadtools.Document.Writer;
using Leadtools.Ocr;
namespace TestAuth.Controllers
{
public class HomeController : Controller
{
List<AdminModel> adminModels = new List<AdminModel>();
interface Iuser
{
public string username { get; set; }
public string password { get; set; }
void IsEqualTo();
}
class User : Iuser
{
public string username { get; set; }
public string password { get; set; }
public void IsEqualTo()
{
throw new NotImplementedException();
}
}
class Admin : Iuser
{
public string username { get; set; }
public string password { get; set; }
public void IsEqualTo()
{
throw new NotImplementedException();
}
}
public IActionResult Index()
{
return View();
}
public IActionResult Index1()
{
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
[HttpPost]
public IActionResult Index1(IFormFile[] files)
{
// Iterate each files
foreach (var file in files)
{
// Get the file name from the browser
var fileName = System.IO.Path.GetFileName(file.FileName);
// Get file path to be uploaded
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);
// Check If file with same name exists and delete it
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
// Create a new local file and copy contents of uploaded file
using (var localFile = System.IO.File.OpenWrite(filePath))
using (var uploadedFile = file.OpenReadStream())
{
uploadedFile.CopyTo(localFile);
}
}
ViewBag.Message = "Files are successfully uploaded";
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename is not availble");
var path = Path.Combine(Directory.GetCurrentDirectory(), "upload", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".csv", "text/csv"}
};
}
public IActionResult Privacy()
{
return View();
}
[HttpGet("denied")]
public IActionResult Denied()
{
return View();
}
[Authorize(Roles ="Admin")]
public IActionResult Secured()
{
return View();
}
[HttpGet("login")]
public IActionResult Login(string returnUrl)
{
ViewData["ReturnURL"] = returnUrl;
return View();
}
[HttpPost("login")]
public async Task<IActionResult> Validate(string username, string password, string returnUrl)
{
ViewData["ReturnUrl"] = returnUrl;
List<Iuser> utilizatori = new List<Iuser>();
utilizatori.Add(new User() { username = "username", password = "password" });
utilizatori.Add(new Admin() { username = "bobitza", password = "28" });
utilizatori.Add(new Admin() { username = "rares", password = "cretin" });
foreach (Iuser user in utilizatori)
{
if(user.username==username && user.password==password)
{
if (user is User)
{
var claims = new List<Claim>();
claims.Add(new Claim("username", username));
claims.Add(new Claim(ClaimTypes.Role, "User"));
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(claimsPrincipal);
}
else if (user is Admin)
{
var claims = new List<Claim>();
claims.Add(new Claim("username", username));
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(claimsPrincipal);
}
}
}
TempData["Error"] = "Error. Username or Password is invlaid";
return View("login");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return Redirect("/");
}
}
}
这是 index1 页面
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
@model FileUploadDownload.Models.FilesViewModel
@{
ViewData["Title"] = "Home Page";
}
<div class="text-left">
<h2 style="margin-bottom:50px">Multiple File Upload</h2>
@if (User.IsInRole("Admin"))
{
<!-- In order to post files to server we should use form with post method, also need to add multipart/form-data encoding.
Otherwise the files will not sent to the server. -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple />
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Alegeti categoria
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Incepatori</a>
<a class="dropdown-item" href="#">Avansati</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Admini</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
<button type="submit">Upload</button>
</nav>
</form>
}
<!-- To show the success message to the user -->
@if (ViewBag.Message != null)
{
<div class="alert alert-success" style="margin-top:50px">
@ViewBag.Message
</div>
}
<p style="margin-top: 50px">List of Files</p>
<!-- Get all the files from the server -->
<ul>
@foreach (var item in Model.Files)
{
<li>
<a asp-action="Download"
asp-route-filename="@item.Name">
@item.Name
</a>
</li>
}
</ul>
</div>
非常感谢
【问题讨论】:
标签: c# asp.net file asp.net-core asp.net-core-mvc