Handle post (from iOS) with image in asp.net server - c#

First, the question briefly:
What I should write in the action parameters for handling the image sent and how to handle data to get the image of it?
What I did is:
Image in iOS converted to NSData (which is a Byte array data if I'm not wrong.
Using AFNetworking to post: to strings that I need in params dict and the image data in
[formData appendWith...].
On the server side, how should my action look like?
Currently it's:
Public JsonResult HandleData (string x, string y, ???????????) {}
The to strings will come from the parameters dictionary but what do I need to do to get the image data and reverse it back to real image?
Thank you so much in advance!

So.. The solution was very simple use in HttpPostedFileBase.
Just added another parameter to my method (HttpPostedFileBase file) and then:
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
file.SaveAs(path);
}
Hope it will be useful for poeple like me that are drowning in much more complex solution out there...

Related

How can I get image content as pixel and create image from it in ASP.NET Core 6 Web API?

I try to save my images on my server, but I can't let my server save file and virus because of that I want to get image content as pixels of rgb and after that I create image by myself.
I can't use bitmap (or other type in C# like bitmapImage, ... etc) and I don't know how I can do this with sixlabors.ImageSharp.
I have some code that I tried but I can't implement the exact logic that I want (code shown here):
[HttpPost("[action]")]
public async Task<IActionResult> Get([FromForm] ImageFormat file)
{
await using var memoryStream = new MemoryStream();
await file.File.CopyToAsync(memoryStream);
IImageFormat format;
using (var image = Image.Load(memoryStream.ToArray(), out format))
{
using (var output = new MemoryStream())
{
image.Save(output, format);
var responseType = format.Name.ToLower();
return File(output.ToArray(), "application/octet-stream", file.File.FileName);
}
}
return null;
}
Can anybody help me with this problem?
i don't see a reason to convert image into image: there are several format zip-algorythms etc.wich you have to support in that case. example jpg is not bitmap, there is convertion issue - quality of image becomes less each conversion time. Image itself is not executable - it can be used only as container for virus body, can't harm your OSystem itself, another executable part should works somewhere.
But even if you would like to store images on disk, in other format - you can convert image to base64 text (one line of code, like example) - it less harmful and well known way to work with any file type. you can zip image by cszip, you can change file name and extension to hide file type.
I don't see a reasson to convert one image to another for this scenario/task.

Convert HttpUploadedFileWrapper to something not in System.Web

I've implemented a file upload in ASP.Net MVC. I've created a view model that received the uploaded file as an HttpPostedFileWrapper and within the controller action I can save the file to disk.
However, I want to perform the actual save in service method which is in a class library that doesn't implement System.Web. I can't therefore pass the HttpPostedFileWrapper object to the service method.
Does anyone know how to achieve this, either by receiving the file as a different object or converting it to something else prior to passing it. The only way I can think of is to read the content of the file into a MemoryStream, and pass this along with the other parameters such as filename individually, but just wondered if there was a better way?
Thanks
The best approach would probably be retrieving the image data (as a byte[]) and the name of the image (as a string) and passing those along to your service, similar to the approach you mentioned :
public void UploadFile(HttpPostedFileWrapper file)
{
// Ensure a file is present
if(file != null)
{
// Store the file data
byte[] data = null;
// Read the file data into an array
using (var reader = new BinaryReader(file.InputStream))
{
data = reader.ReadBytes(file.ContentLength);
}
// Call your service here, passing along the data and file name
UploadFileViaService(file.FileName, data);
}
}
Since a byte[] and a string are very basic primatives, you should have no problem passing them to another service. A Stream is likely to work as well, but they can be prone to issues like being closed, whereas a byte[] will already have all of your content.

Iterating over IEnumerable in view does not print anything

I am trying to print out multiple images using a foreach loop in the view and passing in an IEnumerable<Image> through the model.
My problem is that the foreach loop doesn't display the images at all, and I have no idea what I am doing wrong. I've tried this about 16 different ways and I am still not getting anything other than a broken image link or nothing at all.
Will someone please take a look and see if they can figure out what I am doing wrong? It's probably something very simple and I'm just missing it.
Here is my Controller:
public ActionResult UploadCommission(CommissionViewModel model)
{
List<Image> fileNames = new List<Image>();
//loop through multiple files
foreach (HttpPostedFileBase file in model.Files)
{
//get file names
string filename = System.IO.Path.GetFileName(file.FileName);
//save files
file.SaveAs(Server.MapPath("~/Content/" + filename));
string filepathtosave = "~/Content/" + filename;
fileNames.Add(new Image()
{
FilePath = filepathtosave
});
}
model.ImageFilePaths = fileNames;
return RedirectToAction("ViewComm", model);
}
And here's my View that displayed the information:
#foreach (CapstoneProject.Models.Image i in Model.ImageFilePaths)
{
<img src="#Url.Content(i.FilePath)" />
}
#Model.Title
#Model.Price
#Model.Limit
#foreach (string tag in Model.Tags)
{
<p>#tag</p>
}
#Model.Description
If you need more information, please let me know.
You are using RedirectToAction; according to the docs:
Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.
When you pass that model when redirecting to an action, that data will be lost through the redirection action. What you probably want to do instead is make sure you pass the image URLs in the redirect URL or not use a redirect at all (just render a view)
There's really not enough to work with here to effectively answer your question, but there's nothing obviously wrong with the code you've provided. However, in order for any Image instances to be added to the list they must have been posted in the first place (i.e., if model.Files itself is empty, then so will be your IEnumerable<Image>.
To that end, there's two things you should check:
Ensure that your form has accept="multipart/form-data" on it. Otherwise, uploads will not be posted.
Ensure that your file upload field names are such that they'll bind to the model property on post. In your scenario here, they would need names like Files[N], where N is the index.

How to pass the byte array from flex to dotnet

In my project we need to save the image taken from webcam in a default path using flex 4.6 but giving a default path in flex(saving the image in a default path like C:\temp..) is not possible so we are passing the byte array of that captured image from flex to .ashx page in .net here,image is saving in a default path but imagebytes is not saving(showing that no data in image).If any body knows please let me know.
Finally i got the succeeded in passing the imagebytes from flex to ashx page like below
//Declare a string in script tag(Initialize a string before init() )
[Bindable]public var str64enc:String="";
//creating object for bytearray
[Bindable]public var imgbytes:ByteArray=new ByteArray();
//creating object for bitmapdata
[Bindable]public var picture1:BitmapData=new BitmapData(103,103,true);
**In your code**
var png:PNGEncoder=new PNGEncoder();
imgbytes=png.encode(picture1);
var base64enc:Base64Encoder=new Base64Encoder();
base64enc.encodeBytes(imgbytes);
str64enc=base64enc.toString();
STEP-BY-STEP PROCEDURE:-------
1-Take a base64encoder and encode the bytearray as below:
var base64enc:Base64Encoder=new Base64Encoder();
base64enc.encodeBytes(imgbytes);
2-then assign that base64 encoder object(In this case" base64enc") to string
3-In HTTPSERVICE u need to pass that string like:
<mx:HTTPService id="savepcktdata" method="POST"
url="ur's destination path like..(axis/security/security.aspx)"
result="savepcktdata_resultHandler(event)"
resultFormat="text">
<mx:request>
<Operation>savepcktdata</Operation>
<bytes>
{str64enc}
</bytes>
</mx:request>
</mx:HTTPService>
4- In .aspx page u need to retrieve like:
string str = Convert.ToString(Request.Form["bytes"]);
cocnclusion:In order to pass the image bytes from flex(flash builder 4.6) to dotnet
(visual studio) you need to pass through the base64 string like above code.
Below is the useful link related to this issue
How to pass image from a flex application to a asp net c# web service? asp-net-c-sharp-web-service

Render image from byte[] that is not in the DB in ASP.NET MVC3

This is a variation on a question that has been asked here several times. One example: Display an image contained in a byte[] with ASP.Net MVC3. The question is how to render an image from a byte array.
In all those questions, there is an Action similar to one of the answers in the link I provided above:
public FileContentResult Display(string id) {
byte[] byteArray = GetImageFromDB(id);
return new FileContentResult(byteArray, "image/jpeg");
}
With an image tag similar to this:
<img src="#Url.Action("Display", new { id = Model.Id })" />
This is done because it's not possible to send a byte array through a GET request, so just the id is sent allowing a lookup in the Action method. I get this part, it's not the problem. What I'm trying to do is create a 'Preview' page, where they can check their work before saving in the database. They can see the layout of the Title, Text and Image and decide whether to save, or go back and Edit some more. Therefore, the 'GetImageFromDB(id)' part won't work, since the object has not been saved yet to the database.
Is there any way to accomplish this, or do I just have to save the byte array temporarily in the database and access it that way for the Preview page?
You need to store the uploaded file somewhere on the server if you want to show it later (as a preview or full size image). Whether it is the database or the file system it is up to you. So once the file is uploaded you could store it as a temporary file on some location on the server by renaming it using some unique Guid and return this Guid to the client so that it can create an action link to a preview controller action passing the Guid which will fetch the file from the temporary location and stream it to the client.

Categories

Resources