how to compress Input stream using c#? - 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.

Related

Create Folder Directory to Save file using xamarin plugin extension

I want to create a folder directory and in that folder, I want to save the image and get the response. but when I check manually using file explorer the folder is not showing.
//take picture code
string DirName = "Sample";
string ImgName = "image.jpg";
string basepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
takePhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
byte[] imageArray = null;
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
var stream = file.GetStream();
stream.CopyTo(ms);
imageArray = ms.ToArray();
}
}
Stream data = new MemoryStream(imageArray);
if (file == null)
return;
filePath = file.Path;
paths.Enqueue(filePath);
var result = await CrossEDFSTemplate.Current.SaveFile(basepath, DirName,ImgName, filePath);
await DisplayAlert("Succesful", result.ToString(), "ok");
//Directory create code
public async Task<SaveFileResponse> SaveFile(string FolderBasePath, string FolderName, string
FileName, string FileFullPath = null, Stream data = null)
{
SaveCompletionSource = new TaskCompletionSource<SaveFileResponse>();
if (FolderBasePath != null && FolderName != null)
{
var directoryPath = Path.Combine(FolderBasePath, FolderName);
string NemFilePath = Path.Combine(directoryPath, FileName);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
if (FileFullPath != null)
{
var imageData = File.ReadAllBytes(FileFullPath);
File.WriteAllBytes(NemFilePath, imageData);
}
else if (data != null)
{
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(NemFilePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
else
{
var ResponseSaved = new SaveFileResponse("There are no items to Save", null, FileName);
SaveFileError(this, ResponseSaved);
SaveCompletionSource.TrySetResult(ResponseSaved);
}
}
else
{
return await SaveCompletionSource.Task;
}
return await SaveCompletionSource.Task;
}
according to this code, the directory is creating but when I manually checking that folder using file explorer the folder is not showing.
The path Environment.SpecialFolder.MyPictures you used to save the file is internal storage.
In Internal Storage, you couldn't see the files without root permission.
But you could use the code to check the file exist or not in the internal storage.
if (File.Exists(filepath))
{
}
If you want to view it, you could use adb tool. Please check the way in link.
How to write the username in a local txt file when login success and check on file for next login?

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

Uploading file in ASP.NET to server

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.

How to compress image before upload on amzon s3 server using c# .net?

Hello i have done api for image upload on amzon s3 server with web api c#.but i want to before upload image need this image to compress but how can do that i don't know.
This is my api =>
[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);
SaveJpg(img, filePath); // here i have call method for the save image in my local system.
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = "abc",
InputStream = postedFile.InputStream, // i need this image compress but how can do
Key = path + newFileName
};
PutObjectResponse response = client.PutObject(putRequest);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new Exception("Check the provided AWS Credentials.");
}
else
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
return Request.CreateResponse(HttpStatusCode.OK, Status);
}
}
}
catch (Exception ex)
{
}
return Request.CreateResponse(HttpStatusCode.OK, "Done");
}
This is my ImageCompress method =>
public static void SaveJpg(Image image, string file_name, long compression = 60)
{
try
{
EncoderParameters encoder_params = new EncoderParameters(1);
encoder_params.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, compression);
ImageCodecInfo image_codec_info =
GetEncoderInfo("image/jpeg");
image.Save(file_name, image_codec_info, encoder_params);
}
catch (Exception ex)
{
}
}
This is my api and i need this image to before upload image compress and then after i want to upload this image so any one idea how can do that please let me know.

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