Download file Server Error: The handle is invalid? - asp.net-mvc

public ActionResult FileLink(string hashname)
{
try
{
const string basePath = #"\\WINDHOVERDOCUMENTS\";
const string adminSamples = #"Beta\students\";
return File(basePath + adminSamples + hashname, "application/force-download", hashname);
}
catch (Exception)
{
return null; //no file
}
}
This action simple force user to download the file when the action is triggered. Everything works fine locally. But after publishing to server, it gives me this error. Below is the screenshot. Can anyone help? Thank you. please zoom in to see the screenshot. Sorry.

I solved that by reading the file to byte array then return file content result
var fileBytes = System.IO.File.ReadAllBytes(#"\\path\fileP12.zip");
return File(fileBytes, "application/zip", "package.zip");

Related

File upload from html > mvc/api > remote server

I have a file upload working on html, which calls a post on the api controller.
Could anyone provide / point me in the right direction of the code necessary to get the file out of the post and send that file to an ftp server?
If using an mvc controller is easier that is fine too, although I'd prefer api.
This is the code I currently have - but I don't know how to get an assembled file (an image here, I copy-pasted this from somewhere) out of this data nor how to send it to an ftp server.
[HttpPost]
[Route("api/file/post")]
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
var file = provider.Contents.FirstOrDefault();
if (file == null || file.Headers.ContentDisposition.FileName == null)
return Request.CreateResponse(HttpStatusCode.BadRequest);
using (var ms = new MemoryStream())
{
await file.CopyToAsync(ms);
var byteArray = ms.ToArray();
}
return Request.CreateResponse(HttpStatusCode.Created);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
Any help is appreciated. Thanks in advance.

Failed to load PDF document in MVC

When I first tested this code it seemed to work just fine, but now I am getting a bug.
Failed to load PDF document
I upload a pdf via my admin function, it goes into a database, and then I have an action in my controller that allows a person to download that pdf when it is clicked on.
However, it doesn't seem to work all the time. I also haven't been able to really identify what is causing it to break. If the file size is over 78 kb it seems that Chrome can't open the document while Firefox/Edge can. If the file is under 75 kb Chrome/IE opens it just fine. I am unsure of why this is happening.
I have included my controller below
public ActionResult DownloadPdf(int Id) {
var dbTest = _testRepository.FindId(Id);
var cd = new System.Net.Mime.ContentDisposition { FileName = dbTest.PdfName, Inline = true };
Response.AddHeader("Content-Disposition", cd.ToString());
return File(dbTest.PdfData, "application/pdf");
}
Here is my View
#if (Model.Test.HasPdf)
{
<a data-bind="css: { disabled: !form() }" href="#Url.Action("DownloadPdf", "Test", new { Id = Model.Test.Id })" target="_blank" id="launchBtn" class="btn btn-pdf">Download PDF Form</a>
}
Has anyone else ever had an error like this? If so, how did you fix it?
I figured it out. It had nothing to do with my download feature, it was in my HTTPPost
if (vm.FileData != null)
{
using (var stream = new System.IO.MemoryStream(vm.FileData.ContentLength\\This code between the parenthesis was missing))
{
vm.FileData.InputStream.CopyTo(stream);
test.FileData = stream.GetBuffer();
test.FileName = vm.FileData.FileName;
}
Supposing that your "dbTest" has a property with the PDF content as byte array (byte[]).
To direct download the file
public ActionResult DownloadPdf(int Id) {
var dbTest = _testRepository.FindId(Id);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", $"filename={dbTest.PdfName}");
Response.AppendHeader("Content-Length", dbTest.PdfData.Length.ToString(CultureInfo.InvariantCulture));
Response.BinaryWrite(dbTest.PdfData);
Response.End();
return null;
}
or to open the file in a new browser tab
public ActionResult DownloadPdf(int Id) {
var dbTest = _testRepository.FindId(Id);
return File(dbTest.PdfData, "application/pdf", dbTest.PdfName);
}
I hope this helps you

How to send HttpPostedFileBase to S3 via AWS SDK

I'm having some trouble getting uploaded files to save to S3. My first attempt was:
Result SaveFile(System.Web.HttpPostedFileBase file, string path)
{
//Keys are in web.config
var t = new Amazon.S3.Transfer.TransferUtility(Amazon.RegionEndpoint.USWest2);
try
{
t.Upload(new Amazon.S3.Transfer.TransferUtilityUploadRequest
{
BucketName = Bucket,
InputStream = file.InputStream,
Key = path
});
}
catch (Exception ex)
{
return Result.FailResult(ex.Message);
}
return Result.SuccessResult();
}
This throws an exception with the message: "The request signature we calculated does not match the signature you provided. Check your key and signing method." I also tried copying file.InputStream to a MemoryStream, then uploading that, with the same error.
If I set the InputStream to:
new FileStream(#"c:\folder\file.txt", FileMode.Open)
then the file uploads fine. Do I really need to save the file to disk before uploading it?
This is my working version first the upload method:
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
request.WithBucketName(_bucketName)
.WithCannedACL(S3CannedACL.PublicRead)
.WithKey(filePath).InputStream = inputStream;
request.AddHeaders(AmazonS3Util.CreateHeaderEntry("ContentType", contentType));
_amazonS3Client.PutObject(request);
}
catch (Exception exception)
{
// log or throw;
return false;
}
return true;
}
I just get the stream from HttpPostedFileBase.InputStream
(Note, this is on an older version of the Api, the WithBucketName syntax is no longer supported, but just set the properties directly)
Following the comment of shenku, for newer versions of SDK.
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
string _bucketName = "";
request.BucketName = _bucketName;
request.CannedACL = S3CannedACL.PublicRead;
request.InputStream = inputStream;
request.Key = filePath;
request.Headers.ContentType = contentType;
PutObjectResponse response = _amazonS3Client.PutObject(request);
return true;
}catch(Exception ex)
{
return false;
}
}

FileIOException: File already exists error on blackberry

i get thumbnail image using fileconnection.
I get image using thread constructor. I pass the url and get image.
If the two image url are same , i got exception "FileIOException: File already exists "
My code is here.,
FileConnection fConn = null;
try
{
String fileString = MD5.encodeStringMD5(url);
fConn = (FileConnection) Connector.open(fileTempPath+fileString+".png");
if(!fConn.exists())
{
fConn.create();
GetImageFromURL(url,fConn,id);
}
else
{
GetImageFromFolder(fConn, id);
}
fConn.close();
}
catch (Exception e)
{
System.out.println("------"+e);
}
If the urls are differ. No problem occur. But if two or three url r same , Only one image only stored and load on screen. others same url not displaying.
After stored on device memory, its loadding all image.
The Exception throws in this line - "fConn.create();"
Before creating a new file, try to open a file with the same name/path. If it already exists remove it.
If file already exits then do like this:
if(!fConn.exists())
{
fConn.create();
GetImageFromURL(url,fConn,id);
}
else
{
fConn.truncate();//it removes the data in that file;
GetImageFromFolder(url,fConn, id);
}

"A generic error occurred in GDI+" error while showing uploaded images

i am using the following code to show the image that has been saved in my database from my asp.net mvc(C#) application:.
public ActionResult GetSiteHeaderLogo()
{
SiteHeader _siteHeader = new SiteHeader();
Image imgImage = null;
long userId = Utility.GetUserIdFromSession();
if (userId > 0)
{
_siteHeader = this.siteBLL.GetSiteHeaderLogo(userId);
if (_siteHeader.Logo != null && _siteHeader.Logo.Length > 0)
{
byte[] _imageBytes = _siteHeader.Logo;
if (_imageBytes != null)
{
using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream(_imageBytes))
{
imgImage = Image.FromStream(imageStream);
}
}
string sFileExtension = _siteHeader.FileName.Substring(_siteHeader.FileName.IndexOf('.') + 1,
_siteHeader.FileName.Length - (_siteHeader.FileName.IndexOf('.') + 1));
Response.ContentType = Utility.GetContentTypeByExtension(sFileExtension.ToLower());
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BufferOutput = false;
if (imgImage != null)
{
ImageFormat _imageFormat = Utility.GetImageFormat(sFileExtension.ToLower());
imgImage.Save(Response.OutputStream, _imageFormat);
imgImage.Dispose();
}
}
}
return new EmptyResult();
}
It works fine when i upload original image. But when i upload any downloaded images, it throws the following error:
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(Stream stream, ImageFormat format)
For. Ex: When i upload the original image, it shows as logo in my site and i downloaded that logo from the site and when i re-upload the same downloaded image, it throws the above error. It seems very weird to me and not able to find why its happening. Any ideas on this?
I'd guess that your problem lies here:
using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream(_imageBytes))
{
imgImage = Image.FromStream(imageStream);
}
Because after using .FromStream, the Image owns the stream and might be very upset if you close it. To verify if that's the problem you can just try:
using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream(_imageBytes))
{
imgImage = new Bitmap( Image.FromStream(imageStream) );
}
I've found that error usually comes from a file access problem. Sounds obvious, I realize, but double-check that the file path is correct and that the file exists, and also that the IIS process has permissions to that file.

Resources