Multiple photos upload via Cloudinary.DotNet - image

I have configured my CloudinaryService to upload JUST ONE photo on my cloud on cloudinary. But i have really great troubles with configuring this to make it work on multiple uploads. Please help me, here is my code for single upload:
public async Task<string> UploadPictureAsync(IFormFile pictureFile, string fileName)
{
byte[] destinationData;
using (var ms = new MemoryStream())
{
await pictureFile.CopyToAsync(ms);
destinationData = ms.ToArray();
}
UploadResult uploadResult = null;
using (var ms = new MemoryStream(destinationData))
{
ImageUploadParams uploadParams = new ImageUploadParams
{
Folder = "cars",
File = new FileDescription(fileName, ms),
PublicId = "audizone"
};
uploadResult = this.cloudinaryUtility.Upload(uploadParams);
}
return uploadResult?.SecureUri.AbsoluteUri;
}
}
}
I change IFormFile pictureFile to List<IFormFile> pictureFiles, going on with foreach (file in pictureFiles)...the only thing this service is doing is just uploading 2 or 3 times the same picture(the first one of three or two)...just not uploading two or three different photos.
<form asp-action="Create" method="post" enctype="multipart/form-data">
<input type="file" multiple
class="form-control text-primary text-center"
id="picture"
name="picture"
placeholder="Picture..." />
<input type="submit" value="Submit" class="btn btn-dark" style="border-bottom-left-
radius:25%;border-bottom-right-radius:25%" />
</form>

I managed to successfully loop using this method:
public static void BulkUpload(List<string> filePaths, ResourceType resourceType = ResourceType.Image, string type = "upload")
{
var cloudinary = GetCloudinary(); // Initializing Cloudinary
foreach (var path in filePaths)
{
byte[] bytes = File.ReadAllBytes(path);
var streamed = "streamed";
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
ImageUploadParams uploadParams = new ImageUploadParams()
{
File = new FileDescription(streamed, memoryStream)
};
ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
if (uploadResult.StatusCode == HttpStatusCode.OK)
Console.WriteLine("uploaded: " + uploadResult.PublicId);
else
Console.WriteLine("Failed: " + uploadResult.Error);
}
}
}

Related

uploading image file only _ Spring

I've been started one simple website project to study Spring. I'm trying to check file extension and upload only image file on the board. So I added if else statement before upload file but it dosen't seem working correctly.
My code is below:
#Controller
public class FileUploadController {
#RequestMapping("/write")
public String write(HttpServletRequest request, #RequestParam("bFile") MultipartFile bFile, Model model) {
System.out.println("writeDao()");
String savePath = request.getSession().getServletContext().getRealPath("/fileUpload");
String originalFName = bFile.getOriginalFilename();
String onlyFName = originalFName.substring(0, originalFName.indexOf("."));
String extension = originalFName.substring(originalFName.indexOf(".")); // .jpg
String rename = onlyFName + "_" + getCurrentDayTime() + extension; // fileName_20150721-14-07-50.jpg
String fullPath = savePath + "\\" + rename;
if(!bFile.getContentType().equals("images/jpeg")) {
try{
byte[] bytes = bFile.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(fullPath)));
stream.write(bytes);
stream.close();
System.out.println("Success to upload file");
} catch (Exception e) {
System.out.println("Fail to upload file");
}
} else {
System.out.println("Choose file to upload");
}
String bPwd = request.getParameter("bPwd");
BoardDao dao = sqlSession.getMapper(BoardDao.class);
dao.writeDao(pwd, rename, fullPath);
return "redirect:list";
}
//file upload.jsp
<form action="write" method="post" enctype="multipart/form-data">
<tr>
<td> File </td>
<td> <input type="file" multiple accept='image/*' name="bFile" size = "50"> </td>
</tr>
</form>

How to open remote path pdf in webview xamarin.forms

I am working in xamarin.forms. I got HTML content as josn Response.
<!-- THEME DEBUG --> <!-- CALL: theme('node') --> <!-- FILE NAME SUGGESTIONS: * node--253.tpl.php * node--article.tpl.php x node.tpl.php -->
<!-- BEGIN OUTPUT from 'sites/all/themes/maharastracmonew/templates/node.tpl.php' -->
<div id="node-253" class="node node-article clearfix" about="/maharastracmo/en/magazines" typeof="sioc:Item foaf:Document">
<h2> Magazine Gallery </h2>
<span property="dc:title" content="Magazine Gallery" class="rdf-meta element-hidden"></span>
<span property="sioc:num_replies" content="0" datatype="xsd:integer" class="rdf-meta element-hidden"></span>
<div class="field field-name-body field-type-text-with-summary field-label-hidden">
<div class="field-items">
<div class="field-item even" property="content:encoded">
<div class="innerContent">
<div class="pdfBlock">
<div class="pdfIconBox">
<a href="http://14.141.36.212/maharastracmo/sites/all/themes/maharastracmonew/pdf/MA-June15-binder-6.pdf" target="_blank">
<img alt="" src="http://14.141.36.212/maharastracmo/sites/all/themes/maharastracmonew/images/book-icon.png" />
</a>
<h5>Maharashtra Ahead</h5> <span class="bookDate">June 2015</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div> <!-- END OUTPUT from 'sites/all/themes/maharastracmonew/templates/node.tpl.php' -->
In this content there is one image and on when user click on image .pdf is open in new browser.
I create html and display that html in WebView but on image click pdf file is doesn't open. pdf file is comes from remote device. (Server).
Second Try :
As a second option I have taken webview and simply put pdf remote path as source property but blank page is open. How can I solve this problem?
Third Try :
I simply use one button and on button click event pdf path is open in another browser. but doesn't open instead pdf file is directly download.
protected async void OnClicked(object sender, EventArgs e)
{
var uri = new Uri("http://14.141.36.212/maharastracmo/sites/all/themes/maharastracmonew/pdf/MA-June15-binder-6.pdf");
Device.OpenUri(uri);
}
Need to use Xamarin Dependency Service. Here is how I did it.
First Define an interface:
namespace Mobile.DependencyService
{
/// <summary>
///
/// </summary>
public interface IDownload
{
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="bytes"></param>
/// <param name="fullPathToSavedFile"></param>
void Save(string name, byte[] bytes, out string fullPathToSavedFile);
}
}
Inside your click event: var uri = your link to the pdf;
var uri = repository.GetResumeUri(model);
if (Device.OS == TargetPlatform.Android)
{
using (var clientHandler = new System.Net.Http.HttpClientHandler())
{
using (var httpClient = new System.Net.Http.HttpClient(clientHandler))
{
httpClient.BaseAddress = uri;
byte[] bytes = await httpClient.GetByteArrayAsync(uri);
var service = Xamarin.Forms.DependencyService.Get<Mobile.DependencyService.IDownload>();
string fullPathToSavedFile;
service.Save(
String.Format("{0}.pdf", System.Guid.NewGuid().ToString("N")), //String.Format("{0} Resume.pdf", model.Type),
bytes,
out fullPathToSavedFile
);
uri = new Uri(String.Format("file://{0}", fullPathToSavedFile));
}
}
}
Device.OpenUri(uri);
In iOS:
[assembly: Xamarin.Forms.Dependency(typeof(Mobile.iOS.DependencyService.Download))]
namespace Mobile.iOS.DependencyService
{
public class Download : IDownload
{
public void Save(string name, byte[] bytes, out string fullPathToSavedFile)
{
fullPathToSavedFile = String.Empty;
try
{
fullPathToSavedFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), name);
File.WriteAllBytes(fullPathToSavedFile, bytes);
}
catch (Exception ex)
{
var ex1 = ex;
}
}
}
}
For Android:
[assembly: Xamarin.Forms.Dependency(typeof(Mobile.Droid.DependencyService.Download))]
namespace Mobile.Droid.DependencyService
{
public class Download : IDownload
{
public void Save(string name, byte[] bytes, out string fullPathToSavedFile)
{
fullPathToSavedFile = String.Empty;
// https://developer.xamarin.com/api/type/System.Environment+SpecialFolder/
// http://developer.android.com/guide/topics/data/data-storage.html
try
{
//var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), name);
using(var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads))
{
if (null != directory)
{
var state = Android.OS.Environment.GetExternalStorageState(directory);
if (String.Compare(state, Android.OS.Environment.MediaMounted,true)==0)
{
fullPathToSavedFile = Path.Combine(directory.AbsolutePath, name);
File.WriteAllBytes(fullPathToSavedFile, bytes);
//File.WriteAllBytes(Path.Combine(directory.AbsolutePath, name), bytes);
}
}
}
}
catch(Exception ex)
{
var ex1 = ex;
}
}
}
}

MVC 6 HttpPostedFileBase?

I am attempting to upload an image using MVC 6; however, I am not able to find the class HttpPostedFileBase. I have checked the GitHub and did not have any luck. Does anyone know the correct way to upload a file in MVC6?
MVC 6 used another mechanism to upload files. You can get more examples on GitHub or other sources. Just use IFormFile as a parameter of your action or a collection of files or IFormFileCollection if you want upload few files in the same time:
public async Task<IActionResult> UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
var fileName = parsedContentDisposition.FileName;
}
...
}
[HttpPost]
public async Task<IActionResult> UploadMultiple(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath,"uploads");
foreach(var file in files)
{
if(file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
await file.SaveAsAsync(Path.Combine(uploads,fileName));
}
...
}
}
You can see current contract of IFormFile in asp.net sources. See also ContentDispositionHeaderValue for additional file info.
There is no HttpPostedFileBase in MVC6. You can use IFormFile instead.
Example: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs
Snippet from the above link:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
I was searching around for quite a while trying to piece this together in .net core and ended up with the below. The Base64 conversion will be next to be done so that the retrieval and display is a little easier. I have used IFormFileCollection to be able to do multiple files.
[HttpPost]
public async Task<IActionResult> Create(IFormFileCollection files)
{
Models.File fileIn = new Models.File();
if(model != null && files != null)
{
foreach (var file in files)
{
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
byte[] fileBytes = null;
using (var fileStream = file.OpenReadStream())
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
fileBytes = ms.ToArray();
//string s = Convert.ToBase64String(fileBytes);
// act on the Base64 data
}
fileIn.Filename = fileName;
fileIn.FileLength = Convert.ToInt32(file.Length);
fileIn.FileType = file.ContentType;
fileIn.FileTypeId = model.FileTypeId;
fileIn.FileData = fileBytes;
_context.Add(fileIn);
await _context.SaveChangesAsync();
}
}
}
return View();
}
EDIT
And below is return of files to a list and then download.
public JsonResult GetAllFiles()
{
var files = _context.File
.Include(a => a.FileCategory)
.Select(a => new
{
id = a.Id.ToString(),
fileName = a.Filename,
fileData = a.FileData,
fileType = a.FileType,
friendlyName = a.FriendlyName,
fileCategory = a.FileCategory.Name.ToLower()
}).ToList();
return Json(files);
}
public FileStreamResult DownloadFileById(int id)
{
// Fetching file encoded code from database.
var file = _context.File.SingleOrDefault(f => f.Id == id);
var fileData = file.FileData;
var fileName = file.Filename;
// Converting to code to byte array
byte[] bytes = Convert.FromBase64String(fileData);
// Converting byte array to memory stream.
MemoryStream stream = new MemoryStream(bytes);
// Create final file stream result.
FileStreamResult fileStream = new FileStreamResult(stream, "*/*");
// File name with file extension.
fileStream.FileDownloadName = fileName;
return fileStream;
}

Server.MapPath check for folder and create

I'm uploading an image to a folder images. it's working fine.but what I actually want is to look for a folder name (I have the folder name) if not found create that folder and give it that name.how could that happen?
this is what I have done so far:
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
instead of images I should have folderName.
the complete view:
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("FileUpload", "datum", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div>
category<br />
#Html.DropDownList("category", ViewBag.Roles as SelectList)
<br/>
description<br />
#Html.TextBox("description") <br />
Image<br />
<input type="File" name="file" id="file" value="Choose File" />
<input type="submit" value="Upload" class="submit" />
</div>
}
the complete controller
public class datumController : Controller
{
DataEntry db = new DataEntry();
public ActionResult Index()
{
var data = from p in db.categories
select p.categoryName;
SelectList list = new SelectList(data);
ViewBag.Roles = list;
return View();
}
public ActionResult create ()
{
return View();
}
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
// save image in folder
file.SaveAs(physicalPath);
//save new record in database
datum newRecord = new datum();
newRecord.category = Request.Form["category"];
newRecord.description = Request.Form["description"];
newRecord.imagePath = ImageName;
db.data.Add(newRecord);
db.SaveChanges();
}
//Display records
return RedirectToAction("Display");
}
so I should be getting the selected value from the drop down list and attach it to the physical path, check if folder exists if no then create folder and upload image to that folder
Try like below...
string subPath ="ImagesPath"; // your code goes here
bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
if(!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
For further info, please refer below link.
If a folder does not exist, create it
if (file != null && file.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
tbl_MixEmp.EmpImage = Path.Combine("~/Images", file.FileName);
file.SaveAs(path);
}

Convert that image in thumbnail and save both the images in asp.net-mvc3

upload image by upload control and convert that image in thumbnail and save both file actual image in image folder and thumbnail image in thumbnail Image folder in asp.net-mvc3
I use a 3rd party library called Image Resizer. I struggled with the uploading of images and retaining quality, this library helped me out alot.
In your view:
#model YourProject.ViewModels.ProductImageUploadCreateViewModel
#using (Html.BeginForm("Upload", "ProductImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageFile1" id="ImageFile1">
}
Your controller:
public class ProductImageController : Controller
{
[HttpPost]
public ActionResult Upload(ProductImageUploadCreateViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
if (viewModel.ImageFile1 != null)
{
UploadImage(viewModel.ProductId, "1", viewModel.ImageFile1);
}
// Return to where ever...
}
}
Your upload method:
private void UploadImage(int productId, string imageNo, HttpPostedFileBase imageFile)
{
string uploadPath = Server.MapPath("~/Assets/Images/Products/" + productId);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
Dictionary<string, string> versions = new Dictionary<string, string>();
versions.Add("_m", "width=150&height=150&scale=both&format=jpg"); // Medium size
string filePrefix = productId + "_" + imageNo;
versions.Add("_s", "width=90&height=90&scale=both&format=jpg"); // Small size
versions.Add("_l", "width=300&height=300&scale=both&format=jpg"); // Large size
foreach (string fileSuffix in versions.Keys)
{
// Generate a filename
string fileName = Path.Combine(uploadPath, filePrefix + fileSuffix);
// Let the image builder add the correct extension based on the output file type
fileName = ImageBuilder.Current.Build(imageFile, fileName, new ResizeSettings(versions[fileSuffix]), false, true);
}
}
Have a look on their website, there are a couple of samples that you can work through. I hope this helps :)

Resources