How to cast string to HttpFilePostedBase - asp.net

Is there a way how to convert the string to HttpFilePostedBase?
I'm currently using the Ajax File upload . But the value that it return is string. But my method is requesting for HttpFilePostedBase is there a way how to cast or convert it to HttpFilePostedBase?
here's my sample method in uploading files.
public bool uploadfiles(HttpPostedFileBase filedata)
{
bool status = false;
//code for uploading goes here
return status;
}
How can i call this method if the ajax file upload is passing a string?

Are you using IE or Chrome/Firefox? cause, different browsers upload files in a different manner. IE uploads the files through Requres.Files but others use qqfile in the query string.
Take a look here on how to use valums with mvc for different browsers
EDIT: Okay then, how about this. This is an example which worked for me:
public void ControllerUploadHandler()
{
// Set the response return data type
this.Response.ContentType = "text/html";
try
{
// get just the original filename
byte[] buffer = new byte[Request.ContentLength];
if (Request.QueryString["qqfile"] != null)
{
using (BinaryReader br = new BinaryReader(this.Request.InputStream))
br.Read(buffer, 0, buffer.Length);
}
else if (Request.Files.Count > 0)
{
HttpPostedFileBase httpPostedFileBase = Request.Files[0] as HttpPostedFileBase;
using (BinaryReader br = new BinaryReader(httpPostedFileBase.InputStream))
br.Read(buffer, 0, buffer.Length);
}
else
this.Response.Write(" {'success': false }");
// return the json object as successful
this.Response.Write("{ 'success': true }");
this.Response.End();
return;
}
catch (Exception)
{
// return the json object as unsuccessful
this.Response.Write("{ 'success': false }");
this.Response.End();
}
}

You can't. You can access files posted to an aspx page via the HttpContext.Request.Files property.

Related

How to write HTTP post sending an image file (.jpg/.png) in Unity by using UnityWebRequest?

I want to do a post request in Unity using UnityWebRequest. I have to send a jpg image or png image and the api has to response with a string message or int code.
How to write the C# Script to send the data through post?
Check this out I'm using this method for a long time and it's working for me.
public static IEnumerator CallAPIwithPostAndFileData1(string api_url, List<FileDetails> files, Action<string> callback)
{
WWWForm form = new WWWForm();
int i = 0;
foreach (FileDetails file in files)
{
i++;
UnityWebRequest localFile = UnityWebRequest.Get(#"file://" + file.filePath);
yield return localFile;
form.AddBinaryData("image[]", localFile.downloadHandler.data, file.fileName, "image/" + file.fileType);
}
UnityWebRequest request = UnityWebRequest.Post(api_url, form);
request.SetRequestHeader("Content-Type", "application/json");
request = APIHelper.setAuthToRequest(request, AuthType.BASIC);
request.SendWebRequest();
while (!request.isDone)
{
downloadProgress = request.downloadProgress * 100;
yield return null;
}
if (request.isDone && (!request.isHttpError || !request.isNetworkError))
{
callback(request.downloadHandler.text);
}
else if (request.isHttpError || request.isNetworkError)
{
Debug.LogError(request.error);
}
}
FileDetails This class is only holding some necessary values for me like filepath, fileName, and filetype. It's a bit too long let me know if you don't understand anything.

Generating PDFs using Phantom JS on .NET applications

I have been looking into phantomJS and looks like it could be a great tool to use generating PDFs. I wonder if anyone have successfully used it for their .NET applications.
My specific question is: how would you use modules like rasterize.js on the server, receive requests and send back generated pdfs as a response.
My general question is: is there any best practice for using phantomJS with .NET Applications. What would be the best way to achieve it?
I am fairly new in .NET World and I would appreciate the more detailed answers. Thanks everyone. :)
I don't know about best practices, but, I'm using phantomJS with no problems with the following code.
public ActionResult DownloadStatement(int id)
{
string serverPath = HttpContext.Server.MapPath("~/Phantomjs/");
string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";
new Thread(new ParameterizedThreadStart(x =>
{
ExecuteCommand("cd " + serverPath + #" & phantomjs rasterize.js http://localhost:8080/filetopdf/" + id.ToString() + " " + filename + #" ""A4""");
})).Start();
var filePath = Path.Combine(HttpContext.Server.MapPath("~/Phantomjs/"), filename);
var stream = new MemoryStream();
byte[] bytes = DoWhile(filePath);
return File(bytes, "application/pdf", filename);
}
private void ExecuteCommand(string Command)
{
try
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
Process = Process.Start(ProcessInfo);
}
catch { }
}
public ViewResult FileToPDF(int id)
{
var viewModel = file.Get(id);
return View(viewModel);
}
private byte[] DoWhile(string filePath)
{
byte[] bytes = new byte[0];
bool fail = true;
while (fail)
{
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
}
fail = false;
}
catch
{
Thread.Sleep(1000);
}
}
System.IO.File.Delete(filePath);
return bytes;
}
Here is the action flow:
The user clicks on a link to DownloadStatement Action. Inside there, a new Thread is created to call the ExecuteCommand method.
The ExecuteCommand method is responsible to call phantomJS. The string passed as an argument do the following.
Go to the location where the phantomJS app is and, after that, call rasterize.js with an URL, the filename to be created and a print format. (More about rasterize here).
In my case, what I really want to print is the content delivered by the action filetoupload. It's a simple action that returns a simple view. PhantomJS will call the URL passed as parameter and do all the magic.
While phantomJS is still creating the file, (I guess) I can not return the request made by the client. And that is why I used the DoWhile method. It will hold the request until the file is created by phantomJS and loaded by the app to the request.
If you're open to using NReco.PhantomJS, which provides a .NET wrapper for PhantomJS, you can do this very succinctly.
public async Task<ActionResult> DownloadPdf() {
var phantomJS = new PhantomJS();
try {
var temp = Path.Combine(Path.GetTempPath(),
Path.ChangeExtension(Path.GetRandomFileName(), "pdf")); //must end in .pdf
try {
await phantomJS.RunAsync(HttpContext.Server.MapPath("~/Scripts/rasterize.js"),
new[] { "https://www.google.com", temp });
return File(System.IO.File.ReadAllBytes(temp), "application/pdf");
}
finally {
System.IO.File.Delete(temp);
}
}
finally {
phantomJS.Abort();
}
}
Here's some very basic code to generate a PDF using Phantom.JS but you can find more information here: https://buttercms.com/blog/generating-pdfs-with-node
var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = { width: 1920, height: 1080 };
page.open("http://www.google.com", function start(status) {
page.render('google_home.pdf, {format: 'pdf', quality: '100'});
phantom.exit();
});

HttpHandler [Image] cannot be displayed because it contains errors

Ok i have been working non stop on this and doing a lot of searching. I cannot get my images to display when pulling them from the database. If i try going to the handler link manually i get a message saying "The image [Image] cannot be displayed because it contains errors". I had some old images in the database from before and it first displayed those correctly. But now if i update images it will give me this error when trying to view them.
Upload code.
if (fileuploadImage.HasFile)
{
if (IsValidImage(fileuploadImage))
{
int length = fileuploadImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
if (mainImage == null)
{
ProfileImage image = new ProfileImage();
image.ImageName = txtImageName.Text;
image.ImageData = imgbyte;
image.ImageType = img.ContentType;
image.MainImage = true;
image.PersonID = personID;
if (image.CreateImage() <= 0)
{
SetError("There was an error uploading this image.");
}
}
else
{
mainImage.ImageName = txtImageName.Text;
mainImage.ImageType = img.ContentType;
mainImage.ImageData = imgbyte;
mainImage.MainImage = true;
mainImage.PersonID = personID;
if (!mainImage.UpdateImage())
{
SetError("There was an error uploading this image.");
}
}
}
else
{
SetError("Not a valid image type.");
}
Here is my image handler:
public class ImageHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
int imageid = Parser.GetInt(context.Request.QueryString["ImID"]);
ProfileImage image = new ProfileImage(Parser.GetInt(imageid));
context.Response.ContentType = image.ImageType;
context.Response.Clear();
context.Response.BinaryWrite(image.ImageData);
context.Response.End();
}
And this is how i'm calling it "~/ImageHandler.ashx?ImID=" + Parser.GetString(image.ImageID)
I'm using the data type Image in sql server to store this.
Edit:
I also found out that if i put a try catch around context.Response.end() it is erroring out saying the "Unable to evaluate the code because the native frame..."
I found my problem. I was checking the header of the actual file to make sure it was valid. Somehow that was altering the data and making it bad.

How to cancel and delete the uploading file in asp.net mvc 3?

I am using a filestream to receive a large file in my controller. codes below:
[HttpPost]
public JsonResult Create(string qqfile, Attachment attachment)
{
Stream inputStream = HttpContext.Request.InputStream;
string fullName = ingestPath + Path.GetFileName(qqfile);
using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
{
try
{
var buffer = new byte[1024];
int l = inputStream.Read(buffer, 0, 1024);
while (l > 0)
{
fs.Write(buffer, 0, l);
l = inputStream.Read(buffer, 0, 1024);
}
return Json(new {success = "true"});
}
catch (Exception)
{
return Json(new {success = "false"});
}
finally
{
inputStream.Flush();
inputStream.Close();
fs.Flush();
fs.Close();
}
}
}
And in my page ajax method, I add a button to cancel the file uploading and delete the unfinished file from disk. The ajax request to the action named "Cancel":
[HttpPost]
public JsonResult Cancel(string filename)
{
string localName = HttpUtility.UrlDecode(filename);
string fullName = ingestPath + Path.GetFileName(localName);
if (System.IO.File.Exists(fullName))
{
System.IO.File.Delete(fullName);
}
return Json(new {cancle = true});
}
The problem is: the file can not delete, and the exception message is
the process cannot access the file 'e:\tempdata\filename_xxx.xxx'because it is being used by another process.
I think it is because that ,the filestream of this file is not closed. How can I close this filestream and delete the file in my 'Cancel' action?
--
OH! I found a method to resolve it now.
using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
It is to simple, just declaration a fileshare property: FileShare.Delete
using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write, FileShare.Delete))
I spent 4 hours to google and debug and test and try to resolve it. Just 10 mins after I asked stackoverflow, I got the answer by myself. Interesting! And hope it is useful to someone too.
You could put that file stream in a session then use that session in your cancel action to close the stream.

MVC3 Valums Ajax File Upload

I'm trying to use valums ajax uploader. http://valums.com/ajax-upload/
I have the following on my page:
var button = $('#fileUpload')[0];
var uploader = new qq.FileUploader({
element: button,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
sizeLimit: 2147483647, // max size
action: '/Admin/Home/Upload',
multiple: false
});
it does post to my controller but qqfile is always null. I tried these:
public ActionResult Upload(HttpPostedFile qqfile)
AND
HttpPostedFileBase file = Request.Files["file"];
without any luck.
I found an example for ruby on rails but not sure how to implement it in MVC
http://www.jigsawboys.com/2010/10/06/ruby-on-rails-ajax-file-upload-with-valum/
In firebug i see this:
http://localhost:61143/Admin/Home/Upload?qqfile=2glonglonglongname+-+Copy.gif
I figured it out. this works in IE and Mozilla.
[HttpPost]
public ActionResult FileUpload(string qqfile)
{
var path = #"C:\\Temp\\100\\";
var file = string.Empty;
try
{
var stream = Request.InputStream;
if (String.IsNullOrEmpty(Request["qqfile"]))
{
// IE
HttpPostedFileBase postedFile = Request.Files[0];
stream = postedFile.InputStream;
file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
}
else
{
//Webkit, Mozilla
file = Path.Combine(path, qqfile);
}
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
System.IO.File.WriteAllBytes(file, buffer);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, "application/json");
}
return Json(new { success = true }, "text/html");
}
This component is sending an application/octet-stream instead of multipart/form-data which is what the default model binder can work with. So you cannot expect Request.Files to have any value with such a request.
You will need to manually read the request stream:
public ActionResult Upload(string qqfile)
{
var stream = Request.InputStream;
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
var path = Server.MapPath("~/App_Data");
var file = Path.Combine(path, qqfile);
File.WriteAllBytes(file, buffer);
// TODO: Return whatever the upload control expects as response
}
IE uploads using multipart-mime. Other browsers use Octet-Stream.
I wrote an upload handler to work with Valums Ajax Uploader that works with both MVC & Webforms & both upload methods. I'd be happy to share with you if you wanted. It closely follows the the PHP handler.
My controller to handle the upload looks like this:
public class UploadController : Controller
{
private IUploadService _Service;
public UploadController()
: this(null)
{
}
public UploadController(IUploadService service)
{
_Service = service ?? new UploadService();
}
public ActionResult File()
{
return Content(_Service.Upload().ToString());
}
The UploadService looks this:
public class UploadService : IUploadService
{
private readonly qq.FileUploader _Uploader;
public UploadService()
: this(null)
{ }
public UploadService(IAccountService accountservice)
{
_Uploader = new qq.FileUploader();
}
public UploadResult Upload()
{
qq.UploadResult result = _Uploader.HandleUpload();
if (!result.Success)
return new UploadResult(result.Error);
.... code .....
return new UploadResult((Guid)cmd.Parameters["#id"].Value);
}
catch (Exception ex)
{
return new UploadResult(System.Web.HttpUtility.HtmlEncode(ex.Message));
}
finally
{
............code.........
}
}
...............code ............
You should try:
Stream inputStream = (context.Request.Files.Count > 0) ? context.Request.Files[0].InputStream : context.Request.InputStream;
I am developing in ASP.Net 4.0 but we don't have MVC architecture. I had same issue few days back. But, I figured it out and here is my solution.
//For IE Browser
HttpPostedFile selectedfile = Request.Files[0];
System.Drawing.Bitmap obj = new System.Drawing.Bitmap(selectedfile.InputStream);
//For Non IE Browser
System.Drawing.Bitmap obj = new System.Drawing.Bitmap(Request.InputStream);
Now, you can use obj for further operation.

Resources