I'm trying to implement the file sharing from other apps in Xamarin.Forms.
And I have some issues with Android implementation.
I'm referring to code of https://codemilltech.com/sending-files-to-a-xamarin-forms-app-part-2-android/.
if (Intent.Action == Intent.ActionSend)
{
var uriFromExtras = Intent.GetParcelableExtra(Intent.ExtraStream) as Android.Net.Uri;
string path = Intent.GetParcelableExtra(Intent.ExtraStream).ToString();
var subject = Intent.GetStringExtra(Intent.ExtraSubject);
// Get the info from ClipData
var pdf = Intent.ClipData.GetItemAt(0);
// Open a stream from the URI
var pdfStream = ContentResolver.OpenInputStream(pdf.Uri);
// Save it over
var memOfPdf = new System.IO.MemoryStream();
pdfStream.CopyTo(memOfPdf);
var docsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(docsPath, "temp");
System.IO.File.WriteAllBytes(filePath, memOfPdf.ToArray());
mainForms.ShareFile(memOfPdf.ToArray(), System.IO.Path.GetFileName(path));
}
And I need to get the original name of shared file from File Manager.
Can anyone help me?
Here is a solution that gets the original file name of a shared file through an intent.
if (Intent.Action == Intent.ActionSend)
{
ClipData clip = Intent.ClipData;
Uri uri = clip.GetItemAt(0).Uri;
ICursor returnCursor = ContentResolver.Query(uri, null, null, null, null);
int nameIndex = returnCursor.GetColumnIndex(IOpenableColumns.DisplayName);
returnCursor.MoveToFirst();
var fileName = returnCursor.GetString(nameIndex);
Toast.MakeText(this,"fileName == " + fileName, ToastLength.Short).Show();
}
Examples: .png file and an xls file.
Related
So I am converting an mp3 into wav, using NAudio
Example
string InputAudioFilePath = #"C:\Users\sdkca\Desktop\song.mp3";
string OutputAudioFilePath = #"C:\Users\sdkca\Desktop\song_converted.wav";
using (Mp3FileReader reader = new Mp3FileReader(InputAudioFilePath, wf => new Mp3FrameDecompressor(wf)))
{
WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
}
So in my view model, I am doing the following
I am getting the Documents folder
private static readonly string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Then I am doing this
const string ext = ".wav";
var dlg = new OpenFileDialog
{
Filter = Constants.FILEFILTER
};
var res = dlg.ShowDialog();
if (res! == true)
{
var AudioName = Path.GetFileNameWithoutExtension(dlg.FileName);
var FoderParent = Path.Combine(DocumentsPath, Constants.TRANSCRIPTIONS);
var ParentSubFolder = Path.Combine(FoderParent, Constants.AUDIO);
var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");
using var mp3 = new Mp3FileReader(dlg.FileName);
using var ws = WaveFormatConversionStream.CreatePcmStream(mp3);
WaveFileWriter.CreateWaveFile(filename, ws);
}
I am getting this error
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\egome\OneDrive - Universidad Politécnica de Madrid\Documents\Transcriptions\Audio\10.wav'.'
What I do not understand is, that I am doing a combine between my folder and a new fileName.wav, that is required by the method
Add this check before creating filename string
if(!Directory.Exists(ParentSubFolder))
Directory.CreateDirectory(ParentSubFolder);
var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");
This way, you make sure all path parts exist.
I can not upload any file today!
I said "today" because it was working yesterday. I did not change anything that might be related to that.
I always get this error:
Could not find a part of the path
It is worth mentioning that every configuration is declared in program file.
My Uploader method:
public string Upload(IFormFile? file, string path, string fileToRemove = "")
{
if (file == null)
return "";
var directoryPath = $"{_webHostEnvironment.WebRootPath}/{path}";
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
var fileName = $"{DateTime.Now.ToFileTime()}-{file.FileName}";
var filePath = $"{directoryPath}/{fileName}";
using var stream = File.Create(filePath);
file.CopyTo(stream);
if (!string.IsNullOrEmpty(fileToRemove) ||
!string.IsNullOrWhiteSpace(fileToRemove))
{
var fileToRemovePath = $"{_webHostEnvironment.WebRootPath}/{fileToRemove}";
if (File.Exists(fileToRemovePath))
File.Delete(fileToRemovePath);
}
return $"{path}/{fileName}";
}
I have to save an image in post request in byte64String format
when i save that image i get A generic error occurred in GDI+
here is my code
byte[] ix = Convert.FromBase64String(obj.Image);
var ID = obj.Id;
using (var mStream = new MemoryStream(ix))
{
var img = Image.FromStream(mStream);
var image = obj.ImageName + ".jpg";
string path = HostingEnvironment.MapPath("/Images/" + ImageType + "/" + ID + "/" + image);
System.IO.Directory.CreateDirectory(path);
try
{
img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
var d = e;
}
}
also
this is not a permission issue as i am able to create text files in the same directory
Quite simply you are confusing paths and filenames.
The problem if could hazzard a guess, you probably have a folder that is your filename, and you are trying to save a file with that same name, which windows forbids
Your code tweaked
var image = $"{obj.ImageName }.jpg";
// get the path, and only the path
string path = HostingEnvironment.MapPath($"/Images/{ImageType}/{ID}/");
// Create directory if needed (from that path)
Directory.CreateDirectory(path,image);
...
// now create the correct full path
var fullPath = Path.Combine(path,fileName);
// save
img.Save(fullPath, ImageFormat.Jpeg);
I want to upload an image file and then extract its basic information (author, dimensions, date created, modified, etc) and display it to the user. How can I do it.
A solution or reference to this problem in asp.net c# code would be helpful. But javascript or php would be ok as well.
Check this Link. You will get more Clearance about GetDetailsOf() and its File Properties based on the Win-OS version wise.
If you want to use C# code use below code to get Metadata's:
List<string> arrHeaders = new List<string>();
Shell shell = new ShellClass();
Folder rFolder = shell.NameSpace(_rootPath);
FolderItem rFiles = rFolder.ParseName(filename);
for (int i = 0; i < short.MaxValue; i++)
{
string value = rFolder.GetDetailsOf(rFiles, i).Trim();
arrHeaders.Add(value);
}
C# solution could be found here:
Link1
Link2
Bitmap image = new Bitmap(fileName);
PropertyItem[] propItems = image.PropertyItems;
foreach (PropertyItem item in propItems)
{
Console.WriteLine("iD: 0x" + item.Id.ToString("x"));
}
MSDN Reference
C# Tutorial Reference
try this...
private string doUpload()
{
// Initialize variables
string sSavePath;
sSavePath = "images/";
// Check file size (mustn’t be 0)
HttpPostedFile myFile = FileUpload1.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
//**************
//lblOutput.Text = "No file was uploaded.";
return null;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
//**************
//lblOutput.Text = "The file must have an extension of JPG";
return null;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
return sFilename;
}
I am trying to create a action, in a mvc project. that can upload files and images to my azure storage. but for some reason will it just not upload corrently, that is what i am guessing.
If i upload the image with "Azure Storage Explorere" dose it work fine.
Example: http://storage.sogaard.us/company1/wallpaper-396234.jpg
But if i try to upload the image though my action will it not work, it send a 200 for succes and the right conten type, but the image will not load, and my developer tool tells me i got not data from the server.
Example: http://storage.sogaard.us/company1/b9206edac188e1d8aa2b3be7cdc4b94a.jpg
I have tried to save the uploaded til to my local computer instead of the azure storage and it worked fine there! I can simply not find the reason and this have been bugging me all day :(
Here is my code
[HttpPost]
public ActionResult Upload(FilesUploadModel model, IEnumerable<HttpPostedFileBase> files)
{
if(ModelState.IsValid)
{
if (files != null && files.Any())
{
int maxSizeInBytes = ConfigurationManager.Instance.Configuration.FileMaxSize;
Size thumbSize = new Size(200, 200);
foreach (HttpPostedFileBase file in files.Where(x => x != null))
{
CMS.Common.Data.File _file = new Sogaard.Inc.CMS.Common.Data.File();
// is any files uploadet?
if (!(file.ContentLength > 0))
{
FlashHelper.Add(Text("File not received"), FlashType.Error);
continue;
}
// is the file larger then allowed
if (file.ContentLength > maxSizeInBytes)
{
FlashHelper.Add(Text("The file {0}'s file size was larger then allowed", file.FileName), FlashType.Error);
continue;
}
var fileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now) + Path.GetExtension(file.FileName);
string mimeType = FileHelper.MimeType(FileHelper.GetMimeFromFile(file.InputStream));
_file.SiteId = SiteId();
_file.Container = GetContainerName();
_file.FileName = Path.GetFileName(file.FileName);
_file.FileNameServer = fileName;
_file.Created = DateTime.Now;
_file.Folder = model.Folder;
_file.Size = file.ContentLength;
_file.Type = mimeType;
if (mimeType.ToLower().StartsWith("image/"))
{
try
{
// So we don't lock the file
using (Bitmap bitmap = new Bitmap(file.InputStream))
{
_file.Information = bitmap.Width + "|" + bitmap.Height;
if (bitmap.Height > 500 && bitmap.Width > 500)
{
var thumbfileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + "thumb" + DateTime.Now) + ".jpeg";
Size thumbSizeNew = BaseHelper.ResizeImage(bitmap.Size, thumbSize);
Bitmap thumbnail = (Bitmap)bitmap.GetThumbnailImage(thumbSizeNew.Width,
thumbSizeNew.Height,
ThumbnailCallback,
IntPtr.Zero);
_file.ThumbFileNameServer = thumbfileName;
// Retrieve reference to a blob named "myblob"
CloudBlob blob = container().GetBlobReference(_file.ThumbFileNameServer);
blob.Metadata["Filename"] = Path.GetFileNameWithoutExtension(file.FileName) + "-thumb" + ".jpg";
blob.Properties.ContentType = "image/jpeg";
// Create or overwrite the "myblob" blob with contents from a local file
using (MemoryStream memStream = new MemoryStream())
{
thumbnail.Save(memStream, ImageFormat.Jpeg);
blob.UploadFromStream(memStream);
}
blob.SetMetadata();
blob.SetProperties();
}
}
}
catch (Exception e)
{
if (e.GetType() != typeof (DataException))
FlashHelper.Add(Text("The image {0} was not a valid image", file.FileName),
FlashType.Error);
// Removing the file
System.IO.File.Delete(file.FileName);
}
}
else
{
_file.Information = null;
}
// Retrieve reference to a blob named "myblob"
CloudBlob blobF = container().GetBlobReference(fileName);
blobF.Metadata["Filename"] = file.FileName;
blobF.Properties.ContentType = mimeType;
// Create or overwrite the "myblob" blob with contents from a local file
blobF.UploadFromStream(file.InputStream);
blobF.SetMetadata();
blobF.SetProperties();
fileService.Save(_file);
}
}
return RedirectToAction("Display", new { Folder = model.Folder });
}
model.FolderSugestion = fileService.GetFolders(SiteId());
return View(model);
}
private CloudBlobContainer container()
{
// Retrieve storage account from connection-string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
// Create the blob client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container
var container = blobClient.GetContainerReference(GetContainerName());
container.CreateIfNotExist();
return container;
}
private string GetContainerName()
{
return "company" + SiteId();
}
In the thumbnail code path, I think you need memStream.Position = 0 to reset the stream back to the beginning before trying to upload it.
For the other (non-image) code path, nothing stands out as wrong. Does that code work?
In both code paths, you don't need blob.SetMetadata() and blob.SetProperties(), since those will be done when the upload happens.
[EDIT] Also, what does GetMimeFromFile do? Does it read from the stream (thus perhaps leaving the stream position somewhere other than the beginning)?