ReactJS file upload Axios - reactjs

I am having form with 4 file upload fields, that users can submit up to 4 images.
I am adding files to array, loop and upload to server with PHP.
Now everything seams to be working fine.. but returned image names (I am using those to store in DB) are not in the same order as I am uploading them:
Here is example of code:
if (postImage1 !== null) {
postImagesArray.push(postImage1);
}
if (postImage2 !== null) {
postImagesArray.push(postImage2);
}
if (postImage3 !== null) {
postImagesArray.push(postImage3);
}
if (postImage4 !== null) {
postImagesArray.push(postImage4);
}
//Loop Array and make upload......
var startCount = 1;
var endCount = postImagesArray.length;
for (var i = 0; i < postImagesArray.length; i++) {
var currentImage = postImagesArray[i];
//##### UPLOADING IMAGE ###########
try {
var base_url = 'https://##############.com/uploadImage.php';
var fd = new FormData();
fd.append('avatar', currentImage, 'post.jpg');
axios.post(base_url, fd).then((res) => {
console.log(res);
if (res.data.status === 'success') {
let fileConstruct =
'https://############.com/' +
res.data.fileName +
'?fit=crop&w=840&q=80';
uploadImagesArray.push(fileConstruct);
} else {
// there was an error with file upload... revert to default...
console.log('No error but no image either......');
}
if (startCount == endCount) {
uploadImagesConstruct();
}
startCount++;
});
} catch (err) {
//console.error(err);
console.log(
'There was an error uploading file to the web server: ' + err
);
if (startCount == endCount) {
uploadImagesConstruct();
}
}
Interesting thing is, images are mixed up always in the same order... (so it is not random), instead of returned image1,image2,image3,image4 I am getting image3, image2, image4, image1....If I post only 2 images it is image2,image1.... so first image is always returned last.....
Can anybody see what I am doing wrong..
Thanks!!!!

If anyone need this in the future....
I simply added underscore and postion in the loop "_i" before ".jpg" when I am constructing file names..
fd.append('avatar', currentImage, 'post.jpg');
now is:
fd.append('avatar', currentImage, `post_${i}.jpg`);
and since I am putting all records in the array
uploadImagesArray.push(fileConstruct);
I just resorted it.. by the numbers I added..
uploadImagesArray.sort(function(x, y) {
var xp = x.substring(x.lastIndexOf('_') + 1, x.lastIndexOf('.jpg'));
var yp = y.substring(y.lastIndexOf('_') + 1, y.lastIndexOf('.jpg'));
return xp == yp ? 0 : xp < yp ? -1 : 1;
});

Related

Save UIImage as jpg File in Photo Library Directory in Xamarin.iOS

As I know this is Simple Approch to save it in a Photo Library. But It can save with custom filename.
var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
var o = image as UIImage;
Console.WriteLine("error:" + error);
})
But I want to save it with filename.jpg in the Photo Library.
I try so much code but nothing is getting help to me.
Code 1 :
var imageName = "/" + dicomId.ToString() + ".jpg";
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
This code part goes to if condition but it can not save the Image.
Code 2 :
If using this part of Code
var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];
It give you don't have permission to save image.
I try lots of thing on google and SO but nothing could help to me.
Edit :
info.plist
Any Help would be Appreciated.
How about using UIImage.SaveToPhotosAlbum()?
Usage is something like:
image.SaveToPhotosAlbum((uiImage, nsError) =>
{
if (nsError != null)
// do something about the error..
else
// image should be saved
});
Make sure that you have requested permissions before you try to save.
PHPhotoLibrary.RequestAuthorization(status =>
{
switch (status)
{
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied:
// nope you don't have permission
break;
case PHAuthorizationStatus.Authorized:
// yep it is ok to save
break;
}
});
Edit: if you want more control, you need to use PHPhotosLibrary, which is an awful API...
var library = PHPhotoLibrary.SharedPhotoLibrary;
var albumName = "MyPhotos";
var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
var collection = assetsCollections.firstObject as PHAssetCollection;
library.PerformChanges(() => {
var options = new PHAssetResourceCreationOptions();
options.OriginalFilename = "filename.jpg";
var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);
// if you want to save to specific album... otherwise just remove these three lines
var placeholder = createRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { placeholder });
},
(ok, error) => {
if (error != null)
{
// someone set up us the bomb
}
});

How to Upload Multiple Image Files in a Single Call in Reactjs

Other than workaround of calling fetch multiple times for multiple image files upload (looping through the files), on Frontend, How to upload multiple of image files by just calling fetch/Upload once? Could someone provide a simple example? Just like we do on Facebook.
Thanks in advance!
Update: I am done with looping logic in front end, now as there is loader on every image getting uploaded, Percent uploaded is getting calculated for all images in single value, how to split this value for all images separately?
Looping Logic
for (let i = 0; i <= e.target.files.length; i++){
let reader = new FileReader();
let file = e.target.files[i];
var self = this
reader.onloadstart = () => {
self.setState({ImageUploader: true})
}
reader.onloadend = () => {
var data = reader.result;
if (!file.type.includes('image')) {
alert('PLEASE CHOSE A IMAGE BRAH!')
} else if (file.size / (1024 * 1024) > 5) {
alert('PLEASE CHOSESmaller Image')
} else {
var url = 'https://api......'
var ifd = new FormData();
ifd.append('file', file)
axios({url: url,method: 'put',
onUploadProgress: function(progressEvent) {
var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
self.setState({Completed: percentCompleted})
}, withCredentials: true, data: ifd}).then((res) => {
this.setState({ImageUploader: false})
this.setState({
image_id: this.state.image_id.concat(res.data.reason.image_id)
})
})
this.setState({
file: file,
imagePreviewUrl: this.state.imagePreviewUrl.concat(reader.result),
noImage: false,
ImageChoosen: true
});
}
}
reader.readAsDataURL(file)
}

While inserting image check image size and height

When inserting image in angular i want check image width and height.If width and height does not match i give an error
$scope.imageChanged = function(files,selected_creative_size)
{
$scope.backup_creative_size = '';
if (files != null) {
var file = files[0];
//Here i want to check image size and height
if()
{
//Add data into database
}
else
{
$scope.backup_creative_size = 'Please select' + file_prop[0]+' * '+file_prop[1];
}
}
};
Try using this method on the event onChange this will have maximum size as 3 mb
$scope.uplFile = angular.element("input[type='file']")[0].files[0];
if ($scope.uplFile.size < 3145728) {
if ( $scope.uplFile.type == "image/jpg" || $scope.uplFile.type == "image/jpeg") {
//your code
} else {
//your code
}
} else {
//your code
}

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

Get Count of selected files in Telerik Upload

I need to get a count of all selected files using Telerik MVC Upload Control. Can anyone tell me how can i do that. I tried code like this.
var count = e.files.length;
But its counting always as one.
try this code
[function onSelect(e) {
var selectedFiles = e.files.length;
totalFiles += selectedFiles;
}
function UploadRemove(e) {
totalFiles--;
if (totalFiles > 0) {
// Write true block code here.
}
else if (totalFiles == 0) {
// Write your false block code here.
}
}]
You could do this in your upload event handler:
upload: function (e) {
// File Count:
var fileCount = this.wrapper.find(".k-file").length;
// File Index:
var uid = e.files[0].uid;
var file = this.wrapper.find(".k-file[data-uid='" + uid + "']");
var fileIndex = file.index();
}

Resources