Add file to existing table from ASP.NET MVC - c#

I am just trying to learn ASP.NET MVC and am having an issue, well not so much of an issue but lack of understanding any is not working I am trying to update an SQL table, the code below works fine if I want to delete a table but all I want to do is to add another file to the data table
public async Task<IActionResult> DeleteSnTFileFromFileSystem(int id)
{
var file = await context.SnTModels.Where(x => x.Id == id).FirstOrDefaultAsync();
if (file == null)
return null;
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + file.FilePath);
if (System.IO.File.Exists(basePath))
{
System.IO.File.Delete(basePath);
}
context.SnTModels.Remove(file);
context.SaveChanges();
TempData["Message"] = $"Removed {file.Name + file.Extension} successfully from File System.";
return RedirectToAction("Scenario");
}
Here is my code to create the table
[HttpPost]
public async Task<IActionResult> SnTUploadToFileSystem(List<IFormFile> files, string description)
{
foreach (var file in files)
{
var subPath = "\\*dir file\\";
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + subPath);
bool basePathExists = System.IO.Directory.Exists(basePath);
if (!basePathExists)
Directory.CreateDirectory(basePath);
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var filePath = Path.Combine(basePath, file.FileName);
var extension = Path.GetExtension(file.FileName);
if (!System.IO.File.Exists(filePath))
{
// saving our file to the file system
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
// creating a model and save this model into the db
var SnTModel = new SnTOnFileSystem
{
CreatedOn = DateTime.UtcNow,
FileType = file.ContentType,
Extension = extension,
Name = fileName,
Description = description,
FilePath = subPath + file.FileName
};
context.SnTModels.Add(SnTModel);
context.SaveChanges();
}
}
TempData["Message"] = "File successfully uploaded to File System.";
return RedirectToAction("Index");
}
Here is the post to update the table
[HttpPost]
public async Task<IActionResult> SnTUpdateToFileSystem(List<IFormFile> files, int id)
{
var file = files[0];
var subPath = "\\Training\\SnT\\Document\\";
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + subPath);
bool basePathExists = System.IO.Directory.Exists(basePath);
if (!basePathExists)
Directory.CreateDirectory(basePath);
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var documentFilePath = Path.Combine(basePath, file.FileName);
var extension = Path.GetExtension(file.FileName);
if (!System.IO.File.Exists(documentFilePath))
{
// saving our file to the file system
using (var stream = new FileStream(documentFilePath, FileMode.OpenOrCreate))
{
await file.CopyToAsync(stream);
}
// creating a model and save this model into the db
var SnTModel = new SnTOnFileSystem
{
Name = fileName,
DocumentFilePath = subPath + file.FileName
};
context.SnTModels.Update(SnTModel);
context.SaveChanges();
}
TempData["Message"] = "Document successfully uploaded to File System.";
return RedirectToAction("Scenario");
}

Related

How to Upload a file in Dotnet core 3.1 Web app

Actually I'm try to upload a file from user. But I'm getting error. I tried various way even the Microsoft doc also. I can't help myself. So please help me
Link: Microsoft Doc dotnet core 3.1
My action :
[HttpPost]
public async Task<IActionResult> Updateperson(UpdatePersonViewModel updatePerson)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if(updatePerson.Photo != null)
{
string[] words = updatePerson.Photo.FileName.Split('.');
int a = words.Rank;
uniqueFileName = words[a];
uniqueFileName = Guid.NewGuid().ToString() + "_." + uniqueFileName;
string filePath = Path.Combine("Images",uniqueFileName);
//string filePath = Path.Combine(config["Images"], uniqueFileName);
// using (var stream = System.IO.File.Create(filePath))
// {
// await formFile.CopyToAsync(stream);
// }
await updatePerson.Photo.CopyToAsync(new FileStream(filePath,FileMode.Create));
}
_context.Persons.Update(updatePerson);
_context.SaveChanges();
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
else
{
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
}
>>> config is a object of IConfiguration
Here is Error:
It means no such directory named Image exists!
You can simply check if it exists, or create one if it doesn't exist.
if(!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
To test:
Use a directoryPath variable like this:
var directoryPath=Path.Combine(Directory.GetCurrentDirectory(), "Images");

Upload file in asp.net and angular 7 null

I upload image from angular to .net core but the file input I receive always null , with the postman , it's receive exactly. I don't know why ?
Can you help me how to solve it?
Thank you so much !
[HttpPost("upload-file")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
try
{
//var file = Request.Form.Files[0];
var rnd = FileHelper.RandomNumber();
//var file = file;
var folder = "Folder";
var index = file.FileName.LastIndexOf('.');
var onlyName = file.FileName.Substring(0, index);
var fileName = onlyName + rnd;
var extension = Path.GetExtension(file.FileName);
var folderThumb = folder + "Thumbnail";
var fileNameThumb = fileName + "Thumbnail";
var t1 = Task.Run(() => FileHelper.SaveFile(folder, fileName, file));
await Task.WhenAll(t1);
var path = new MediaResponseModel()
{
Url = Url.Action("GetFile", "Media", new { folder = folder, fileName = string.Format("{0}{1}", fileName, extension) }, Request.Scheme),
UrlThumbnail = Url.Action("GetFile", "Media", new { folder = folderThumb, fileName = string.Format("{0}{1}", fileNameThumb, extension) }, Request.Scheme),
Title = onlyName
};
return Ok(path);
}
catch (System.Exception e)
{
throw e;
}
}
handleFileInput(files: FileList) {
const file = files.item(0);
this.fileToUpload = {};
this.fileToUpload.data = files.item(0);
this.fileToUpload.fileName = files.item(0).name;
}
onUpload() {
const formData = new FormData();
formData.append('file', this.fileToUpload.data, this.fileToUpload.name);
this.http.post('http://localhost:56000/api/media/upload-file', formData).subscribe(res => console.log(res));
}

.NET Google Drive API - Get files with parent folder

Is there any possible way to get the list of files with parent folder name and without making additional queries?
My Files.List() code sample:
var sheets = new List<File>();
var sheetsRequest = Service.Files.List();
sheetsRequest.Fields = "nextPageToken, files(id, name, owners, parents)";
sheetsRequest.Q = $"mimeType = '{mimeType}' and name = '{name}'";
sheetsRequest.PageSize = 500;
var sheetsFeed = await sheetsRequest.ExecuteAsync();
while (sheetsFeed.Files != null)
{
foreach (var file in sheetsFeed.Files)
{
sheets.Add(file);
}
if (sheetsFeed.NextPageToken == null)
break;
sheetsRequest.PageToken = sheetsFeed.NextPageToken;
sheetsFeed = await sheetsRequest.ExecuteAsync();
}
return sheets;
Because for now I making GetFileParentDirAsync call for each File using following method (and it's very slow):
public async Task<string> GetFileParentDirAsync(File file)
{
return await Task.Run(async () =>
{
var folderName = string.Empty;
if (file.Parents?.First() == null) return folderName;
var parentId = file.Parents.First();
var parentRequest = Service.Files.Get(parentId);
var parentResponse = await parentRequest.ExecuteAsync();
folderName = parentResponse.Name;
return folderName;
});
}
Thanks.

Migrate ParentReference from Google Drive Apis v2 to v3 in C#.Net

After reading the migration infos from Google on the Gdrive.v3 SDK here: https://developers.google.com/drive/v3/web/migration, I#m still not really sure how I can set the ParentReference (to the root folder) for a file correctly. Currently in v2 this is done via:
private string UploadToGDrive( Google.Apis.Drive.v3.DriveService service, string uploadFile, string parent)
{
var body = new Google.Apis.Drive.v3.Data.File
{
Name = Path.GetFileName(uploadFile),
Description = uploadFile,
MimeType = GetMimeType(uploadFile),
Parents = new List<ParentReference> {new ParentReference {Id = parent}}
};
}
private string GetMimeType(string fileName)
{
var mimeType = "application/unknown";
var extension = Path.GetExtension(fileName);
if (extension == null) return mimeType;
var ext = extension.ToLower();
var regKey = Registry.ClassesRoot.OpenSubKey(ext);
if (regKey?.GetValue("Content Type") != null) return mimeType;
if (regKey != null) mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
As stated in the document - Inserting a file in a folder:
To insert a file in a particular folder, specify the correct ID in the parents property of the file, as shown:
var folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
var fileMetadata = new File()
{
Name = "photo.jpg",
Parents = new List<string>
{
folderId
}
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
Hope this helps.
I must have overseen this... It simply means in my case to replace
var body = new Google.Apis.Drive.v3.Data.File
{
Name = Path.GetFileName(uploadFile),
Description = uploadFile,
MimeType = GetMimeType(uploadFile),
Parents = new List<ParentReference> {new ParentReference {Id = parent}}
};
with
var body = new Google.Apis.Drive.v3.Data.File
{
Name = Path.GetFileName(uploadFile),
Description = uploadFile,
MimeType = GetMimeType(uploadFile),
Parents = new List<string> {parent}
};
(I've added this as an answer as it is to long for a comment).

Saving image path on db and images into folder asp .net mvc

I have issue in uploading images path into database and moving imagesg into folder, here is code:
public ActionResult UploadImages(
HttpPostedFileBase formFilled,
HttpPostedFileBase sixPics,
HttpPostedFileBase buyerCNIC,
HttpPostedFileBase sellerCNIC
)
{
if (Session["user"] == null)
{
return RedirectToAction("Login", "User");
}
CustomerDocumentImages dbCustomerDocs = new CustomerDocumentImages();
string recieverName = Request.Form["RecieverName"];
var allowedExtensions = new[] {
".Jpg", ".png", ".jpg", "jpeg"
};
dbCustomerDocs.FormFilledPhysicalPath = formFilled.ToString();
var _formFilled = Path.GetFileName(formFilled.FileName); //getting only file name(a.jpg)
var ext = Path.GetExtension(formFilled.FileName);
if (allowedExtensions.Contains(ext))
{
string name = Path.GetFileNameWithoutExtension(_formFilled); //getting file name without extension
string formImage = name + "_" + DateTime.Now + ext; //appending the name with id
// store the file inside ~/project folder(Img)
var path = Path.Combine(Server.MapPath("~/Images"), formImage);
dbCustomerDocs.FormFilledPhysicalPath = path;
dbCustomerDocs.FormFilled = _formFilled;
dbCustomerDocs.RecieverName = recieverName;
try
{
var currentAllotmentId = Convert.ToInt32(Request.Form["AllotmentId"]);
var dbAllotment = db.Allotments.SingleOrDefault(i => i.AllotmentId == currentAllotmentId);
dbCustomerDocs.AllotmentId = dbAllotment.AllotmentId;
dbAllotment.IsCustomerDocsUploaded = true;
}
catch (Exception)
{
ModelState.AddModelError("", "Please select valid allotment");
}
db.CustomerDocumentImagess.Add(dbCustomerDocs);
db.SaveChanges();
formFilled.SaveAs("~Images"+path);
return RedirectToAction("Index");
}
else
{
ViewBag.message = "Please choose only Image file";
}
return View();
}
I have also used server.mappath but it woking fine on localhost but giving error on windows live server( on save as method ) , in case of combine.mappath works fine but not moving image into folder. please guide me, thanks in advance.

Categories