This is my first time asking around here, so sorry if it's not worded very well.
I have a blazor WebAssembly project with MudBlazor, and when I try to upload files to save them into a database, it appears the next error message in the browser console.
System.IO.FileNotFoundException: Could not find file
When the user uploads the files I call the next method to save the files into IList<IBrowserFile>.
IList<IBrowserFile> Files = new List<IBrowserFile>();
private void OnInputFileChanged(InputFileChangeEventArgs e)
{
var files = e.GetMultipleFiles();
foreach(var file in files)
{
Files.Add(file);
}
}
Once the user has uploaded all the files, they click on a button that call the next method to upload it into a database.
[Inject] protected ISnackbar Snackbar { get; set; } = default!;
private async void Upload()
{
List<string>? notUploadFiles = null;
foreach(var file in Files)
{
byte[] fileBytes = File.ReadAllBytes(destPath + file.Name);
string extn = new FileInfo(file.Name).Extension;
var addArchivoTarea = new AddArchivoTareaRequestDTO(Tarea.Id, fileBytes, extn);
var successResponse = await HttpTareas.AddArchivoToTareaAsync(addArchivoTarea);
if (!successResponse)
{
notUploadFiles.Add(file.Name);
}
}
if(notUploadFiles is not null) {
Snackbar.Configuration.SnackbarVariant = Variant.Filled;
Snackbar.Add("The following files could not be uploaded:", Severity.Info);
Snackbar.Configuration.SnackbarVariant = Variant.Outlined;
foreach (var file in notUploadFiles)
{
Snackbar.Add(file, Severity.Error);
}
//Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter;
//Snackbar.Add("TODO: Upload your files!", Severity.Normal);
MudDialog.Close(DialogResult.Ok(true));
}
Snackbar.Add("All files have been successfully uploaded", Severity.Success);
MudDialog.Close(DialogResult.Ok(true));
}
I don't know where is the problem, any idea?
The uploaded files are not in the file system, they are in-memory only. The way to access the raw data would be something like:
byte[] fileBytes;
using (Stream s = file.OpenReadStream())
{
MemoryStream ms = new MemoryStream();
await s.CopyToAsync(ms);
fileBytes= ms.ToArray();
}
Related
I try to do a function which of the files from the zip file will take two values and update them in the GUI.
the problem is that i get exception about access to the file.
System.IO.IOException: 'The process cannot access the file 'C:\work\RasMol.zip' because it is being used by another process.'
public void ReplaceEntry(string fileName)
{
var infoList = new List<RPPXFileEntry>();
{
ZipArchive Archive = ZipFile.Open(this.sourcePath, ZipArchiveMode.Update);
//exception in this place
foreach (ZipArchiveEntry entry in Archive.Entries)
{
var rppxEntry = new RPPXFileEntry();
if (entry.Name == fileName)
{
rppxEntry.Modify = entry.LastWriteTime;
rppxEntry.Size = entry.Length;
infoList.Add(rppxEntry);
}
}
this.AllEntries = infoList;
}
}
someone know how to deal with it?
Here i am trying to open the file of any extension format in ASP.NET MVC CORE 2.0 that has been saved in data base according to the extension format of that file without downloading that file. For example lets say i have ms word file so when i click that file it should open in word, if i have pdf it should open in pdf format without downloading the file.
Now, the problem in my code is that it force to download the file instead of opening the file according to respective file extemsion format.
Any help will be a great and will be thank full.Thank You
Below is my code
public IActionResult ViewFileByFileId (int id)
{
DoctorCredentialDocsModel DoctorCredential = new DoctorCredentialDocsModel();
DoctorCredential = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, DoctorCredential.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
if (!strFileFullPath.Contains("..\\"))
{
byte[] filedata = System.IO.File.ReadAllBytes(strFileFullPath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = DoctorCredential.FileName,
Inline = false,
};
Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
else
{
return new NotFoundResult();
}
}
Try yo send like tihs. FileContentResult may can help you :)
Lastly look at this :)
What's the difference between the four File Results in ASP.NET MVC
public FileContentResult ViewFileByFileId (int id)
{
DoctorCredentialDocsModel DoctorCredential = new DoctorCredentialDocsModel();
DoctorCredential = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, DoctorCredential.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
if (!strFileFullPath.Contains("..\\"))
{
byte[] filedata = System.IO.File.ReadAllBytes(strFileFullPath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = DoctorCredential.FileName,
Inline = false,
};
Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
else
{
return new NotFoundResult();
}
}
I'm using Xam.Plugin.Media to take a picture .
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions()
{
Directory = "attachments",
Name = fileName,
CompressionQuality = 35
});
cam.Source = ImageSource.FromFile(file.Path);
above code does work !
file path is (file.Path):
/var/mobile/Containers/Data/Application/F3997E36-78EB-41AF-A37F-FC794BAF30EC/Documents/attachments/13c8ac4e57734a36bded2c2694e27495.jpg
but this code does not show picture in an Image control
var q = "/var/mobile/Containers/Data/Application/F3997E36-78EB-41AF-A37F-FC794BAF30EC/Documents/attachments/13c8ac4e57734a36bded2c2694e27495.jpg"
cam.Source = ImageSource.FromFile(q);
On iOS, this is the way to load file you saved before. This is because the system regenerate UDID every time the app relaunch.
public Stream LoadSampleStream(string filename) {
try
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath = Path.Combine(documentsPath, "Sample", filename);
return new FileStream(filePath, FileMode.Open);
}
catch(Exception ex) {
return null;
}
}
You need to save photo in gallery. When your user takes a photo it will still store temporary data, but also if needed make a copy to the public gallery
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true
});
Get the public album path
var aPpath = file.AlbumPath;
Get private path
var path = file.Path;
I have an application that allows a user to upload a file, the file is scanned with Symantec protection engine before it is saved. The problem I'm encountering is that after the files are scanned with protection engine they have 0 bytes. I'm trying to come up with a solution to this problem.
I've tried the cloning solution mentioned here: Deep cloning objects, but my uploaded files are not all Serializable. I've also tried resetting the stream to 0 in the scan engine class before passing it back to be saved.
I have been in contact with Symantec and they said the custom connection class that was written for this application looks correct, and protection engine is not throwing errors.
I'm open to any solution to this problem.
Here is the code where the file is uploaded:
private void UploadFiles()
{
System.Web.HttpPostedFile objFile;
string strFilename = string.Empty;
if (FileUpload1.HasFile)
{
objFile = FileUpload1.PostedFile;
strFilename = FileUpload1.FileName;
if (GetUploadedFilesCount() < 8)
{
if (IsDuplicateFileName(Path.GetFileName(objFile.FileName)) == false)
{
if (ValidateUploadedFiles(FileUpload1.PostedFile) == true)
{
//stores full path of folder
string strFileLocation = CreateFolder();
//Just to know the uploading folder
mTransactionInfo.FileLocation = strFileLocation.Split('\\').Last();
if (ScanUploadedFile(objFile) == true)
{
SaveFile(objFile, strFileLocation);
}
else
{
lblErrorMessage.Visible = true;
if (mFileStatus != null)
{ lblErrorMessage.Text = mFileStatus.ToString(); }
I can provide the connection class code if anyone needs that, but it is quite large.
You could take a copy of the filestream before you pass it into the scanning engine.
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
// pass the scanning engine
StreamScanRequest scan = requestManagerObj.CreateStreamScanRequest(Policy.DEFAULT);
//...
Update
To copy the stream you can do this:
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
file.InputStream.Position = ms.Position = 0;
I have a to create a routine that will unzip multiple zip files( average size of the zip will be 2GB) in parallel. So, I created a function that using TPL to unzip the files.
This works well in principle. I don't have test data yet so i figured I would make a copy of the zip file that currently exists and rename the files in it and rezip it. Well, I am getting the following error when I do that:
the archive entry was compressed using an unsupported compression method
Well please comment on the code as you see fit and why am I getting the error here.
Code:
private static void UnzipfilesInTemp()
{
Task[] unzippers = null;
bool rtn = false;
//--UNZIP FILES IN TEMPORARY LOCATION
var TEMP_ZIP_FILES = System.IO.Directory.GetFiles(tempPath, "*" + Statement*.zip");
unzippers = new Task[TEMP_ZIP_FILES.Length];
unZippedFiles = new string[TEMP_ZIP_FILES.Length];
lock (thisLock)
{
for (int i = 0; i <= TEMP_ZIP_FILES.Length - 1; i++)
{
string filename = TEMP_ZIP_FILES[i];
unzippers[i] = Task.Factory.StartNew(() =>
{
//--UNZIP FILE FOR STATEMENT IMPORTING
try
{
ZipFile.ExtractToDirectory(filename, tempPath);
}
catch (Exception)
{
//--UNABLE TO UNZIP FILES
_coreprocess.AddLogDetailRecord(MSG, false, "");
ProcessSuccess = false;
ExitAllCode();
}
});
}
}
Task.WaitAll(unzippers);
unZippedFiles = System.IO.Directory.GetFiles(tempPath, "*" + BANK_NUM + "*.PDF");
}