How to integated plupload into asp.net MVC2 project - c#

I try to use plupload in my asp.net MVC2 project, can I do it?
Please help me if it can.
Best regards!

it is same as normal file upload but i like plupload i will use on my project so following codes will work with plupload
[HttpPost]
public ActionResult Create(FormCollection collection)
{
// my project need single file upload so i get the first file
// also you can write foreach statement to get all files
HttpPostedFileBase postedFile = Request.Files[0];
Image image = new Image();
if (TryUpdateModel(image))
{
fRepository.AddImage(image);
fRepository.Save();
// Try to save file
if (postedFile.ContentLength > 0)
{
string savePath = Path.Combine(Server.MapPath("~/Content/OtelImages/"), image.ImageID.ToString() +
Path.GetExtension(postedFile.FileName));
postedFile.SaveAs(savePath);
// Path for dbase
image.Path = Path.Combine("Content/OtelImages/", image.ImageID.ToString() +
Path.GetExtension(postedFile.FileName));
}
i didn't change the codes, but if you need any further help please ask, i'll explain

Related

How can I save an image at server in ASP.NET Core MVC using C#? [duplicate]

I'm recently working on a ReactJS app that's calling an API (developed with .NET Core 2.0).
My question is how to use HttpPostedFileBase in an .NET Core 2.0 API in order to get file content and save it in database.
You don't have HttpPostedFileBase in ASP.NET Core 2.0, but you can use IFormFile.
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
More here: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1
IFormFile is in the following namespace Microsoft.AspNetCore.Http.
HttpPostedFileBase doesn't exist in ASP.NET Core. You should use IFormFile now, instead. However, that only works when you send the request as multipart/form-data, which you're likely not doing if you're working with a client-side framework like React. If you're posting JSON, you should set the JSON member that corresponds with your file property with the file encoded as a Base64 string. Server-side, you should then bind to byte[].
If anyone finds this by searching for HttpPostedFileBase it's possible you're familiar with writing ASP.NET controller methods something like this:
public async Task<IActionResult> DoThing(MyViewModel model, HttpPostedFileBase fileOne, HttpPostedFileBase fileTwo)
{
//process files here
}
If you're wanting to write an equivalent in ASP.NET Core then you can write it like this:
public async Task<IActionResult> DoThing(MyViewModel model, IFormFile fileOne, IFormFile fileTwo)
{
//process files here
}
i.e. the only change needed to the method signature is replacing HttpPostedFileBase with IFormFile. You will then need to modify your method to work with the new parameter type (e.g. HttpPostedFileBase has an InputStream property, whereas IFormFile has a OpenReadStream() method) but I think the details of those differences are beyond the scope of this question.
You should also be able to get the files like this :
[HttpPost]
public ActionResult UploadFiles()
{
var files = Request.Form.Files;
return Ok();
}

MVC multiple file download

I have to ask a suggestion about a project I'm following. I need to create an action inside an MVC controller that let me download a series of images directly and not by compressing them inside a zip archive. I tried to achieve that by calling a download function inside the action, like this:
foreach(var image in images){
var imageFilename = image.filename;
var imageName = image.text;
var mimeType = image.type;
DownloadFile(imageFilename, imageName, mimeType);
}
Setting download file as
public FileResult DownloadFile(string imageFilename, string imageName, string mimeType){
return File(imageFilename, imageName, mimeType);
}
But this not works. Do you have any suggestion on how to proceed on this to avoid zip archive? Or is the only suitable method for this problem?

Decompress base64 zipstream

I want to make a plug-in which can transfer the zip file from web to asp.net mvc background and decompress it into my server.
In my website, i choose a zip file
<input type="file" id="FileZip">
and post it's value to my asp.net method
public async Task<string> FileTrs(string Zip)
Then i got the string of the following type
data:application/x-zip-compressed;base64,
How can i unzip it into my server ?
Could anybody tell me, thanks!
I would do something like this and then use for example the SharpZip-lib to decompress my file.
[HttpPost]
public async Task<string> FileTrs()
{
if (Request.Files.Any)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
// Unzip file here with for example SharpZipLib
}
}
}
Examples for how to use SharpZip here
Maybe you need to convert the uploaded file to a stream before using it in the SharpoZipLib.
For .Net Framework 4.5 and higher!! This shall be applicable
Answers how to Unzip, If you have access to server, It shall not be an Issue.
static void Extractor()
{
string whereMyZIPFileIs = #"path\fileName.zip";
string whereIWantToExtract = #"pathOfExtraction";
System.IO.Compression.ZipFile.ExtractToDirectory(whereMyZIPFileIs, whereIWantToExtract);
}
Please add "System.IO.Compression.FileSystem.dll" to Reference

How to use ImageResizer in C# .NET/MVC4

I'm working on a site where I need to crop and resize images that people upload.
I got the code for the upload function but in my httpPost action result I want to resize the image to start off with. I also got the code for that but I can't find a way to show the image.
Here is my code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
foreach (string fileKey in System.Web.HttpContext.Current.Request.Files.Keys)
{
HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[fileKey];
if (file.ContentLength <= 0) continue; //Skip unused file controls.
ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, "~/img/", new ImageResizer.ResizeSettings("width=50;height=50;format=jpg;mode=max"));
i.CreateParentDirectory = true; //Auto-create the uploads directory.
i.Build();
string relativePath = "~/img/" + Path.GetFileName(uploadFile.FileName);
string physicalPath = Server.MapPath(relativePath);
uploadFile.SaveAs(physicalPath);
return View((object)relativePath);
}
}
I want go write out the Image information from ImageResizer.ImageJob i..
Any ideas?
Thank you!
First, the code you're using allows anybody to upload an executable page and run it.
Never, under any circumstances, should you use uploadFile.FileName as part of the final path name, unless you deeply understand path and length sanitization.
Second, ImageJob needs a destination path, not a folder path. You can use variables, like "~/img/<guid>.<ext>" and access the resulting physical path from i.FinalPath. You can use ImageResizer.Util.PathUtils.GuessVirtualPath(i.FinalPath) to get the app-relative path.
As this is almost a precise duplicate of mvc3 ImageResizer, please consider using the search feature before posting.

How to upload multiple files to server with form post MVC?

I am working on a project of Asp.Net MVC-4. In my project user post requirements. Post contains title, tags, files etc.File may be multiple and it may be of any type like Video, doc ( ppt, excel, pdf, etc), images etc.
My problem is the handling of multiple file upload. Now first of all i tell you
currently how i am handling this :
I am using Jquery FIle Uplaod plugin. Through this plugin i am uploading file to server sequentially and on server i am saving those file with SessionId.Now when user post there requirement form than i just rename those file with userId.
drawback of my approach
First i have to save those files with session id and than i have to rename it with userId. So if i save my file in Window Azure Blobs than in that case for uploading single file i have to do 2 transaction. First save the blob with SessionId and than Renaming the blob with userid. Which i think result extra processing and extra cost.
Now i want to know if there is any approach by which i can upload all file (with progress bar for individual file [required]) with form post. So that user's requirement form (tags, titile etc) with all files go to server together than in that case i will save the user first in the database and than i will save the files with the userId ??
Note: I cannot save File with guid or other. UserId is required in the file name to uniquely identify user's files.
You can upload using following code in controller
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
foreach (var file in files) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
more details here
Not sure if i completely understand the question, but you could post the model for your user details in the same POST as the file upload (same form?), then on the server:
[HttpPost]
public JsonResult AddNewImage(UserModel user)
{
ReturnArgs r = new ReturnArgs();
repo.AddUser(user) // add your user to DB here
SaveImages(user.Id);
r.Status = 200;
r.Message = "OK!";
return Json(r);
}
private void SaveImages(string userid)
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i] as HttpPostedFileBase;
string fileName = userid + "_" + i;
// saving file to DB here, but you can do what you want with
// the inputstream
repo.SaveImage(fileName, file.InputStream, file.ContentType);
}
}

Categories