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)?
Related
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.
I am trying to create a Windows app which uploads files to FTP. Essentially, it looks for .jpeg files in a given folder, it reads through the barcodes found in the .jpg files before uploading it into the FTP server, and entering the URL into the database for our records.
As there will be multiple files at any given time in the folder, I am essentially trying to read them in a loop, and process them accordingly. However, I get an OutOfMemoryException whenever the loop starts again. I am trying to figure out what I'm doing wrong here. I have appended my code below:
private void btnProcess_Click(object sender, RoutedEventArgs e)
{
podPath = Directory.GetFiles(DestPath, "*.jpg");
List<string> scans = new List<string>(podPath.Length);
List<string> badscans = new List<string>();
byte[] imageBytes;
string filename, result;
POD conpod = new POD();
OTPOD otpod = new OTPOD();
ConsignmentObj scanJob;
//Pickup OTScan;
//Consolidate ccv;
for (int i = 0; i < podPath.Count(); i++ )
{
filename = podPath[i].ToString();
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename))
{
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
if (result != null)
{
//if barcode can be read, we throw the value into the database to pull out relevant information
if (result.Contains(ConNotePrefix))
{
#region Consignments
scanJob = getCon(result.ToString());
final = ImageFolder + "\\" + result.ToString() + ".jpg";
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
MemoryStream ms = new MemoryStream();
try
{
img.Save(ms, ImageFormat.Jpeg);
imageBytes = ms.ToArray();
img.Dispose();
}
finally
{
ms.Flush();
ms.Close();
ms.Dispose();
}
}
lock (filename)
{
if (System.IO.File.Exists(filename))
{
File.Delete(filename);
}
}
using (var stream = File.Create(final)) { }
File.WriteAllBytes(final, imageBytes);
File.Delete(filename);
conpod.ConsignmentID = scanJob.ConsignmentID;
conpod.UserID = 1;
conpod.Location = ftpUrl + "//" + result.ToString() + ".jpg";
conpod.rowguid = Guid.NewGuid();
UploadFilesToFtp(ftpUrl, ftpUser, ftpPass, final, result.ToString() + ".jpg");
insertPOD(conpod);
scans.Add(result.ToString());
#endregion
}
}
else
{
badscans.Add(filename);
}
}
this.lbScans.ItemsSource = scans;
this.lbBadScans.ItemsSource = badscans;
}
The FTP method, UploadFilesToFtp(x, x, x, x, x, x) is not a problem here. All feedback will be much appreciated.
An OutOfMemoryException can also be thrown by the method FromFile of the Image class when
The file does not have a valid image format.
or
GDI+ does not support the pixel format of the file.
So i think there is a problem with one of your image files you are reading. One solution is to catch the OutOfMemoryException and adding the file to the badscans.
try{
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename)) {
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
}
catch(OutOfMemoryException) {
badscans.add(filename);
}
I am trying to upload JPG file to a folder I have created in my project.
The image does not get saved in the images folder. It displays my image when I upload but the image itself is not present in images folder.
Here is the code i am using:
private void btnUpload_Click(object sender, System.EventArgs e)
{
// Initialize variables
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;
// Set constant values
sSavePath = "images/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;
// If file field isn’t empty
if (filUpload.PostedFile != null)
{
// Check file size (mustn’t be 0)
HttpPostedFile myFile = filUpload.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Text = "No file was uploaded.";
return;
}
// 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;
}
// 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();
// Check whether the file is really a JPEG by opening it
System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
// If jpg file is a jpeg, create a thumbnail filename that is unique.
file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}
// Save thumbnail and output it onto the webpage
System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
imgPicture.ImageUrl = sSavePath + sThumbFile;
// Displaying success information
lblOutput.Text = "File uploaded successfully!";
// Destroy objects
myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}
}
public bool ThumbnailCallback()
{
return false;
}
I'd be surprised if the line myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile)); works...
You are trying to map a file which doesn't exist yet!
Try
myThumbnail.Save(Server.MapPath(sSavePath) + sThumbFile));
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 have working code that uses signature pad data to create and save a signature bmp image to a file location. My question is: how can I modify this code to insert the image into a SQL Server 2008 image field?
The following from my Controller obtains signature data from a signature tablet and creates a bmp image and saves it to a file location.
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public ActionResult SaveSignature2(IPrincipal principal) {
int userId = ((ScoutIdentity)principal.Identity).UserId.Value;
//Put user code to initialize the page here
SIGPLUSLib.SigPlus sigObj = new SIGPLUSLib.SigPlus();
sigObj.InitSigPlus();
sigObj.AutoKeyStart();
string visitorname = Request.Form["visitorname"];
visitorname = visitorname.Replace(" ", ""); //combines the first name with last name with no spaces
visitorname = visitorname.Trim();
string thevrvIDstr = Request.Form["vrvID"];
int thevrvID = Convert.ToInt32(thevrvIDstr);
//use the same data to decrypt signature
sigObj.AutoKeyData = Request.Form["SigText"];
sigObj.AutoKeyFinish();
sigObj.SigCompressionMode = 1;
sigObj.EncryptionMode = 2;
//Now, get sigstring from client
//Sigstring can be stored in a database if
//a biometric signature is desired rather than an image
sigObj.SigString = Request.Form["hidden"];
if (sigObj.NumberOfTabletPoints() > 0) {
sigObj.ImageFileFormat = 0;
sigObj.ImageXSize = 500;
sigObj.ImageYSize = 150;
sigObj.ImagePenWidth = 8;
sigObj.SetAntiAliasParameters(1, 600, 700);
sigObj.JustifyX = 5;
sigObj.JustifyY = 5;
sigObj.JustifyMode = 5;
long size;
byte[] byteValue;
sigObj.BitMapBufferWrite();
size = sigObj.BitMapBufferSize();
byteValue = new byte[size];
byteValue = (byte[])sigObj.GetBitmapBufferBytes();
sigObj.BitMapBufferClose();
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteValue);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
String path;
path = System.AppDomain.CurrentDomain.BaseDirectory;
path = path + "/uploadFiles/Signatures/"+thevrvIDstr+".bmp";
img.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
ViewData["Result"] = ("Image saved successfully to " + path);
}
else {
ViewData["Result"] = "signature has not been returned successfully!";
}
ViewData["Result"] = sigObj.SigString;
//return RedirectToAction("vrSignIn");
return View();
}
I also have code elsewhere in my controller that gets an uploaded file and inserts it into the database. This code works OK.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadTempFiles(string id, string u)
{
//this method temporarily stores files
string userIdString = Cryptographer.DecryptSymmetric("RijndaelManaged", SecurityImpl.UrlToBase64(u));
int userId = Convert.ToInt32(userIdString);
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
int contentlength = file.ContentLength;
byte[] b = new byte[contentlength];
Stream s;
s = file.InputStream;
s.Read(b, 0, contentlength);
VisitRequest.AddVisitorSignature(userId, b);
}
}
return View("UploadFiles");
}
I'm thinking that I can use some part of the second code to interrupt the image creation process in the first code and insert the image into the database INSTEAD of saving the image to a file location. I don't know how to do that.
I had same problem, and I solved it:
Comment these three lines:
//path = System.AppDomain.CurrentDomain.BaseDirectory;
//path = path + "/uploadFiles/Signatures/"+thevrvIDstr+".bmp";
//img.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
Convert image to String data (assumed that your variable 'strSignature' was declared before):
strSignature = img.ToString();
Save it with your Stored Procedure.
Hope this help you!