Uploading file in ASP.NET to server - c#

I'm working on a website where users could apply to a certain job online.
A user must submit information in addition to a CV.
I'm new to this kind of work I would appreciate any kind of help.
Here is my attempt for the post method, but it generates the following exception:
Unexpected end of stream. Is there an end boundary?
public async Task<IHttpActionResult> PostCV()
{
IList<string> AllowedFileExtensions = new List<string> { ".txt", ".pdf" };
var parser = new MultipartFormDataParser(await Request.Content.ReadAsStreamAsync());
IList<FilePart> files = parser.Files;
IList<ParameterPart> formData = parser.Parameters;
FilePart uploadedContent = files.First();
var originalContentFileName =
uploadedContent.FileName.Trim('\"');
var originalExtension = Path.GetExtension(originalContentFileName);
if (!AllowedFileExtensions.Contains(originalExtension))
return BadRequest("Bad extension");
string modifiedContentFileName =
string.Format("{0}{1}", Guid.NewGuid().ToString(),
originalExtension);
Stream input = uploadedContent.Data;
string Url = string.Empty;
string fileName = string.Empty;
string directoryName = string.Empty;
directoryName = Path.Combine(HttpRuntime.AppDomainAppPath, "Uploads");
fileName = Path.Combine(directoryName, modifiedContentFileName);
if (File.Exists(fileName))
File.Delete(fileName);
using (Stream file = File.OpenWrite(fileName))
{
try
{
input.CopyTo(file);
file.Close();
var cv = new CV{ Path = fileName };
db.CVs.Add(cv);
db.SaveChanges();
return Json(cv);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
Thanks in advance

Apparently I should have chosen form-data in the body section, set the key with anything (e.g filename) and in the value choose file.
Also you need to create a folder in your path, in my case called Uploads in the directory specified.
Lots of thanks for those who helped.

Related

Download Files into a certain path in the internal Storage { C# Xamarin }

currently I am curious how to download files on your android device and save the file to a certain path on the INTERNAL STORAGE. My result I want to get at the end is: If the User click on a button it start to download and replace the file in the path that is defined.
Appreciate any help!
With my current code i tried to modify it directly, but had no success...
Wish y´all a Great Day & thanks for reading!
*Frost
Renegade = new Command(async () =>
{
string pak5 = "";
Stream stream1 = File.OpenRead(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "Android/data/com.epicgames.fortnite/files/InstalledBundles/FortniteBR/FortniteGame/Content/Paks/pakchunk10_s5-Android_ASTCClient.ucas");
/*using (var streamWriter = new StreamWriter(pak5, true))
{
streamWriter.WriteLine(DateTime.UtcNow);
}
using (var streamReader = new StreamReader(pak5))
{
string content = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(content);
}*/
StreamReader reader = new StreamReader(stream1);
string pakspath = reader.ReadToEnd();
//80000000
//80000000
//System.IO.File.Delete("/storage/emulated/0/Android/data/com.epicgames.fortnite/files/InstalledBundles/FortniteBR/FortniteGame/Content/Paks/pakchunk10_s5-Android_ASTCClient.ucas ");
//Utilities.Convert(Body, Body1, pakspath, 80000000);
//Utilities.Convert(Mat, Mat1, pakspath, 8981062);
ReplaceBytes(pakspath, 8981045, S1);
ReplaceBytes(pakspath, 8981045, S2);
ReplaceBytes(pakspath, 80782548, S3);
ReplaceBytes(pakspath, 80782548, S4);
ReplaceBytes(pakspath, 80782571, S5);
ReplaceBytes(pakspath, 80782571, S6);
});
If you are using Xamarin forms then ,Here is my solution.Make a class like this on your
Android project.
public class DroidFileHelper
{
public string GetLocalFilePath(string filename)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
return Path.Combine(path, filename);
}
public async Task SaveFileToDefaultLocation(string fileName, byte[] bytes, bool showFile = false)
{
Context currentContext = Android.App.Application.Context;
string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string file = Path.Combine(directory, fileName);
System.IO.File.WriteAllBytes(file, bytes);
//If you want to open up the file after download the use below code
if (showFile)
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N)
{
string externalStorageState = global::Android.OS.Environment.ExternalStorageState;
var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + global::Android.OS.Environment.DirectoryDownloads + "/" + fileName;
File.WriteAllBytes(externalPath, bytes);
Java.IO.File files = new Java.IO.File(externalPath);
files.SetReadable(true);
string application = "application/pdf";
Intent intent = new Intent(Intent.ActionView);
Android.Net.Uri uri = FileProvider.GetUriForFile(currentContext, "com.companyname.appname.provider", files);
intent.SetDataAndType(uri, application);
intent.SetFlags(ActivityFlags.GrantReadUriPermission);
Forms.Context.StartActivity(intent);
}
else
{
Intent promptInstall = new Intent(Intent.ActionView);
promptInstall.SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(file)), "application/pdf");
promptInstall.SetFlags(ActivityFlags.NewTask);
Forms.Context.StartActivity(promptInstall);
}
}
}
}
after that call it like from your xamarin form.
Xamarin.Forms.DependencyService.Get<IFileHelper>().SaveFileToDefaultLocation(oFile.FileName, oFile.FileInBytes, true);
It will save your file to Downloads because we set the path as Android.OS.Environment.DirectoryDownloads in our droid helper class

file storage .net core

i'm using a folder inside my project to upload files .
[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources", "Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
i was wondering if there's a risk to lose this files when we have new update for the customer .
if there's a better solution for upload file and getting file link afterwards with .net core please let me know :)
i was wondering if there's a risk to lose this files when we have new update for the customer
Deploying an application means, you'll copy the new executables (dlls) and other files stored in git to the place where the old version is running. Risk is, that you'll do it wrong and delete the data directory.
That said: You should not save user data together with your executables or other files that are part of your app (e.g. images used in HTML, ...). It's much easier to handle (backups, deployments, ...) if data is clearly separated.
if there's a better solution
The solution: Save it in a folder that can be configured by admins. This can be done using so called Options: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1
You'll end up with a class that stores your path
public class StorageOptions {
public string BasePath {get;set;}
}
so at the end i decided to use 'aws S3 bucket' using this code
PutObjectResponse response = null;
using (var stream = new MemoryStream(fileBytes))
{
var request = new PutObjectRequest
{
BucketName = bucket,
Key = "folder/" + fileName,
InputStream = stream,
ContentType = file.ContentType,
CannedACL = S3CannedACL.PublicRead,
};
response = await client.PutObjectAsync(request);
};
and as you mentioned in comments i can get the link afterwards of the file

how to compress Input stream using c#?

I have write code for the image upload using c# web api. now i want to image upload done with on server. and this thing is also done.but i want to compress the image then after upload on server. but how can do i have no idea any one know how can do that then please let me know. i want to compress image then upload on amzon s3 server using webapi.
This is my code =>
[HttpPost]
[Route("FileUpload")]
public HttpResponseMessage FileUpload()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
string fname = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName.ToString());
string extension = Path.GetExtension(postedFile.FileName);
Image img = null;
string newFileName = "";
string path = "";
img = Image.FromStream(postedFile.InputStream);
string path = ConfigurationManager.AppSettings["ImageUploadPath"].ToString();
newFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpeg";
string filePath = Path.Combine(path, newFileName);
UploadImageOnServer(postedFile.InputStream,path + newFileName);
}
}
}
catch (Exception ex)
{
}
return Request.CreateResponse(HttpStatusCode.OK, "Done");
}
This is my server on upload code =>
public static void UploadImageOnServer(Stream File, string Key)
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = Bucketname,
InputStream = File,
CannedACL = S3CannedACL.PublicRead,
Key = Key
};
PutObjectResponse response = client.PutObject(putRequest);
}
This is my code now i want to compress image. please any one know then please let me know.

Why do I get a permission error in the OpenUrl function on an iOS device when trying to read in the file that has been sent to my app?

I have my Info.plist file setup to handle the file type I want. When I download the file in Safari, and pick my App from the Open In, the file does get sent to my app and the OpenUrl function is called. In the Simulator, I am able to open the file using FileStream and process it without any problem. On the real device, I get an error that says something like:
Accesss to the path "/private/var/mobile/Containers/Data/Application/{KEY}/Documents/Inbox/file.ext is denied.
Here is my OpenUrl function:
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
try
{
System.Console.WriteLine("OpenURL");
var fileName = url.AbsoluteUrl.LastPathComponent;
var newPath = Path.Combine(bookStorage, fileName);
var input = new System.IO.FileStream(url.Path, FileMode.Open);
var output = new System.IO.FileStream(newPath, FileMode.Create);
input.CopyTo(output);
output.Close();
input.Close();
var epub = new EpubParser(bookStorage, fileName);
var publication = new Publication(epub.getTitle(), fileName);
var id = epub.getId();
if (id != null)
{
publication.Id = id;
}
publication.Picture = epub.getImage();
var publications = new Publications();
publications.AddPublication(publication);
return true;
}
catch (Exception e)
{
var navController = (UINavigationController)this.Window.RootViewController;
var controller = navController.ViewControllers[0];
AlertView.Show(e.Message, controller);
return false;
}
}
Basically all I wanted was to copy the file to another location to keep it stored. So I used File.Copy instead and it worked! Apparently FileStream even with just the Open permissions set, still requires some type of write access to the folder.
var fileName = url.AbsoluteUrl.LastPathComponent;
var newPath = Path.Combine(bookStorage, fileName);
File.Copy(url.Path, newPath);

How to Copy URI path file into temp folder?

I have a file path in URI and trying to copy the URI file into C:\temp\ but I am getting an error "Could not find file (from the URI path)" If anyone suggest me would be a great helpful. Thank you.
public String getFile(String uri)
{
// Download file in temp folder
String fileName = Path.GetFileName(uri.Replace("/", "\\"));
Uri fileUri = new Uri(uri);
string fullFilePath = absoluteUri.AbsoluteUri.ToString();
string localPath = new Uri(fullFilePath).LocalPath;
String tempFolder = #"C:\temp\";
File.Copy(localPath, tempFolder);
return fileName;
}
You can use web client to download a file from a Uri
new WebClient().DownloadFile(uri, Path.Combine(filePath, fileName));
I tried in a different way and its working for me. I hope this could help for someone else.
private String getFile(String uri)
{
Uri uriFile = new Uri(uri);
String fileName = Path.GetFileName(uri);
List<String> fileData = new List<String>();
// Reads all the code lines of a file
fileData = readCodeLines(uriFile);
String tempPath = #"c:\temp\";
try
{
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
File.WriteAllLines(tempPath, fileData);
}
catch (IOException ex)
{
MessageBox.Show("Could not find the Temp folder" + " " + tempPath);
}
return fileName;
}

Categories

Resources