I am having issues with refreshing a partial view after post. what I want is to post some files, after they are uploaded I want to refresh a partial view. on a different partial view I delete the item and it refreshes ok, but on this partial it doesn't work. I got to some point were I can see that the refresh method is called before the AddImages and i still can't figure it out why the method is called and the data does not update.
I tried several methods here is where I am now :
Partial View-
<div id="UploadImages">
<form asp-page-handler="AddImages" id="imageUploadForm" method="post" data-ajax="true" data-ajax-method="post" data-ajax-update="#ProductImages">
<div class="card-body">
<h3>Edit Product Images</h3>
<input asp-for="#Model" multiple="multiple" id="ctl_images" name="upload_file" class="form-control" onchange="preview_image();" />
</div>
<button class="btn btn-sm btn-primary d-none d-md-inline-block" type="submit" id="AddImages" onclick="clickbtn();">
Add
</button>
</form>
<div id="image_preview">
</div>
</div>
Scripts to preview the uploaded image and to post to the razor page without refreshing the page, just the form:
<script>
//preview Images to upload.
function preview_image() {
total_file = document.getElementById("ctl_images").files.length;
for (var i = 0; i < total_file; i++) {
$('#image_preview').append("<span class=\"pip\">" +
"<img class='img-preview' id='previmg" + i + "'src='" + URL.createObjectURL(event.target.files[i]) + "'>"
+ "<br/><button class=\"btn-close\" aria-label='Close'></button>" + "</span>");
$('.btn-close').click(function () {
$(this).parent(".pip").remove();
$('#previmg' + i).click(function () { (this).remove(); });
});
}
}
//Load multiple Images to product catalog.
function clickbtn() {
var files = document.getElementById('ctl_images').files;
var url = window.location.pathname + "?handler=AddImages";
formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("CatalogImages", files[i]);
}
jQuery.ajax({
type: 'POST',
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
document.getElementById("imageUploadForm").reset();
var prv= document.getElementById("image_preview");
prv.innerHTML = "";
//if (repo.status == "success") {
// alert("File : " + repo.filename + " is uploaded successfully");
//}
},
error: function () {
alert("Error occurs");
},
});
}
Page model :
public async Task<IActionResult> OnPostAddImagesAsync()
{
var pathCtl = Path.Combine(_webHostEnvironment.WebRootPath, "Images/CatalogImages");
//if (!ModelState.IsValid)
// return Page();
//CatalogImages = (IFormFileCollection)Request.Form["ctl_Images"].ToList();
try
{
ProductImages = new List<ProductImageViewModel>();
foreach (var image in CatalogImages)
{
var uniqueFileName = string.Concat(Guid.NewGuid().ToString(), image.FileName);
using var fileStream = new FileStream(Path.Combine(pathCtl, uniqueFileName), FileMode.Create);
var productImage = new ProductImageViewModel
{
ImageUrl = Path.Combine("Images/CatalogImages", uniqueFileName),
ProductId = Product.Id,
};
await image.CopyToAsync(fileStream);
ProductImages.Add(productImage);
}
foreach (var item in ProductImages)
{
await _productImageRepo.Add(item, User);
}
var result = await OnPostRefreshImagesAsync(Product.Id);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return Page();
throw ex;
}
}
public async Task<IActionResult> OnPostRefreshImagesAsync(int id)
{
var productImages = await _productImageRepo.GetByProductId(id);
var result = new PartialViewResult
{
ViewName = "~/Pages/Partials/_ProductImagesCardGroup.cshtml",
ViewData = new ViewDataDictionary<List<ProductImageViewModel>>(ViewData, productImages),
};
return result;
}
I ended up adding this code line to make it work. it seems posting questiosn here gives me inspiration.
$('#ProductImages').html(response);
//Load multiple Images to product catalog.
function clickbtn() {
var files = document.getElementById('ctl_images').files;
var url = window.location.pathname + "?handler=AddImages";
formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("CatalogImages", files[i]);
}
jQuery.ajax({
type: 'POST',
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
document.getElementById("imageUploadForm").reset();
var prv = document.getElementById("image_preview");
prv.innerHTML = "";
**$('#ProductImages').html(response);**
//if (repo.status == "success") {
// alert("File : " + repo.filename + " is uploaded successfully");
//}
},
error: function () {
alert("Error occurs");
},
});
Related
I am trying to upload a profilePhoto from reactjs to express backend using FormData:
const form = new FormData();
form.append(user, "user");
form.append(profilePhoto, "profilePhoto");
axios({
method: "post",
url: "http://localhost:8082/candidate/addCandidate",
data: form,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
in the backend : (this works well with the postman and the image gets added to the backend)
const DIR = "./public/";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
const fileName = file.originalname.toLowerCase().split(" ").join("-");
cb(null, uuid() + "-" + fileName);
},
});
var upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (
file.mimetype === "image/png" ||
file.mimetype === "image/jpg" ||
file.mimetype === "image/jpeg"
) {
cb(null, true);
} else {
cb(null, false);
return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
}
},
});
router.post(
"/addCandidate",
upload.single("profilePhoto"),
(req, res, next) => {
const url = req.protocol + "://" + req.get("host");
// try {
const candidate = new Candidate({
user: req.body.user,
profilePhoto: url + "/public/" + req.file,
});
candidate
.save()
.then((result) => {
console.log("bbbbbbbbbbbb", req);
res.status(201).json({
message: "User registered successfully!",
profilePhoto: result.profilePhoto,
});
})
.catch((err) => {
console.log("aaaaaaaaaaaa", req.body.file);
res.status(500).json({ error: err });
console.log(err);
});
}
);
however, when ever i try to upload a file it doesnt get uploaded to the backend and i get req.file undefined. I tried to console the req and this is what i get body:
{'606aee02f057cd714db2b646': 'user', '[object File]': 'profilePhoto'}
Any help!
I use something like this, you can change it for your project
My component:
import React from "react";
import ConfigX from '../ConfigX'
class FileUploader extends React.Component
{
url_upload = "";
url_download = "";
apiKey = "";
typ = "news";
typ_id = 99999;
constructor(props)
{
super(props)
this.state = {
view: "list",
title: "wybierz plik",
files: [],
uploadProcentAll: 10,
}
this.url_upload = ConfigX.restApi + "/rest,file_upload";
this.url_download = ConfigX.restApi + "/rest,file_list";
this.url_delete = ConfigX.restApi + "/rest,file_delete";
this.apiKey = this.props.apiKey;
this.typ = this.props.typ;
this.typ_id = this.props.typ_id;
}
/**
* Get actual list of file uploaded to server
*/
componentDidMount()
{
var dataPost = {
};
fetch( this.url_download , {
method: 'POST',
body: JSON.stringify(dataPost),
headers: {
'Content-Type': 'text/html',
'X-API-KEY': this.apiKey
}
})
.then( res => res.json() )
.then(json => {
// this.setState({
// files: json
// });
});
}
onChangeInput(event)
{
var handle = event.target;
console.log("FileUploader, selected: " + handle.files.length );
if( handle.files.length == 0) return false;
for(var i = 0; i < handle.files.length; i++)
{
var file = handle.files[i];
var isAdded = false;
this.state.files.forEach( exFile => {
if(exFile.name == file['name']) isAdded = true;
});
if(isAdded) continue;
var randName = crypto.getRandomValues( new Uint32Array(1)) + file['name'];
var item = {
name: file['name'],
progress: 0,
status: 'start',
uq: randName
}
var list = this.state.files;
list.push(item);
this.setState({ files: list});
this.startUpload(file, list.length-1, randName );
}
}
onDelete(event)
{
var uq = event.target.getAttribute("uq");
console.log("FileUploader, delete: " + uq);
var dataPost = {
uq: uq
};
fetch( this.url_delete , {
method: 'POST',
body: JSON.stringify(dataPost),
headers: {
'Content-Type': 'text/html',
'X-API-KEY': this.apiKey
}
})
.then( res => res.json() )
.then(json => {
if(json.status == "OK") //deleted on server..
{
var files = this.state.files.filter( item => {
if(item.uq == uq) return false;
return true;
} );
this.setState({
files: files
})
}
});
}
refreshProgress()
{
var sumP = 0;
var countP = 0;
this.state.files.map( item => {
if(item.status == 'start' || item.status == 'upload')
{
countP++;
sumP += item.progress;
}
} );
var avg = sumP / countP;
this.setState({
uploadProcentAll: avg
});
}
startUpload(file, tabIndex, randName)
{
var refState = this.state;
var refRefreshProgress = this.refreshProgress.bind(this);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress',function(ev)
{
var procent = (ev.loaded/ev.total );
procent *= 100;
procent = Math.round(procent) ;
refState.files[tabIndex]['progress'] = procent;
refState.files[tabIndex]['status'] = "upload";
refRefreshProgress();
}, false)
xhr.addEventListener("load", function(ev){
} , false);
xhr.addEventListener("error", function(ev){}, false);
xhr.addEventListener("abort", function(ev){}, false);
xhr.onreadystatechange = function(ev)
{
if (xhr.readyState == 4)
{
refState.files[tabIndex]['status'] = "finish";
refState.files[tabIndex]['progress'] = 100;
}
};
xhr.open('POST', this.url_upload, true);
xhr.setRequestHeader('X-API-KEY', this.apiKey);
var data = new FormData();
data.append('file'+tabIndex, file );
data.append('typ', this.typ);
data.append('typ_id', this.typ_id);
data.append('fileUploader','yes');
data.append('uq', randName);
xhr.send(data);
}
render()
{
var progress = "";
var progressStyle = {
width: this.state.uploadProcentAll+"%"
}
if(this.state.uploadProcentAll > 0 && this.state.uploadProcentAll < 100 )
{
progress = (
<div className="progressBar">
<div className="progressLine" style={progressStyle}>{this.state.uploadProcentAll}</div>
</div>
)
}
return (
<div className="fileUploader">
<div className="buttonUploader">
<input type="file" onchange="zaladuj_pliki(this)" multiple id="fileselect" name="fileselect[]" accept="*/*" onChange={this.onChangeInput.bind(this)} />
{progress}
</div>
<table>
{
this.state.files.map( (item,index) => {
return (
<tr key={index} >
<td>{item.progress}</td>
<td>{item.name}</td>
<td uq={item.uq} onClick={this.onDelete.bind(this) } >Del</td>
</tr>
)
})
}
</table>
</div>
)
}
}
export default FileUploader;
Put in parent:
<FileUploader typ="sk_szkolenia" typ_id={this.state.rows.id} apiKey={this.props.apiKey} />
I have a form like that in nuxt :
<v-form v-if="displayForm" ref="form" v-model="valid" enctype="multipart/form-data" lazy-validation>
<v-flex xs12 md6 sm12>
<v-text-field
v-model="linkOriginal"
label="Link to the original work (not required)"
/>
</v-flex>
<v-flex xs12 md6 sm12>
<span>Pic from original work (required)</span>
<input id="file" ref="file" type="file" #change="handleFileUpload()">
</v-flex>
</v-form>
And my script is like that :
<script>
export default {
data() {
return {
file: "",
linkOriginal: "",
};
},
methods: {
handleFileUpload() {
console.log(this.$refs.file.files[0]);
this.file = this.$refs.file.files[0];
},
submit() {
if (this.$refs.form.validate()) {
let formData = new FormData();
formData.append("file", this.file);
formData.append("notifDate", this.notifDate)
this.$axios
.post(
"http://mynodeserver.com:3000/infringement",
formData,
{
headers: {
"Access-Control-Allow-Origin": true
"Content-Type": "multipart/form-data"
}
}
)
.then(response => {
this.displayForm = false;
this.displayError = false;
this.displaySuccess = true;
})
.catch(e => {
this.displayForm = false;
this.displaySuccess = false;
this.displayError = true;
});
} else {
console.log("u need to complete the required elements");
}
},
clear() {
this.$refs.form.reset();
}
}
};
</script>
On my node server-side part when I console log req.body.file or req.body.notifDate it returns undefined so I can't attach it to the email I want to send with nodemailer. what am I missing here?
The axios.post() request is taking an object as a second parameter, axios.post('/api/submit', {data: formData})
I'm using the CMA directly (no SDK). I am trying to upload a file to Contenful. From what I've read the flow is this:
Upload the file
Create an asset(associating it to the recently uploaded file)
Process the asset
I am uploading the file like this:
const xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 201) {
let data: any = JSON.parse(xhr.response);
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
const url = "https://upload.contentful.com/spaces/" + space_id + "/uploads";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.setRequestHeader("Authorization", "Bearer " + token);
const formData = new FormData();
formData.append("file", file, file.name);
xhr.send(formData);
Then I create the asset like this:
const request = {
fields: {
file: {
"en-US": {
contentType: file.type,
fileName: file.name,
uploadFrom: {
sys: {
type: "Link",
linkType: "Upload",
id: uploadId
}
}
}
}
}
};
return axios
.post(
"https://api.contentful.com/spaces/" + space_id + "/assets",
JSON.stringify(request),
config
)....
and then process it like this:
const request = {
fields: {
file: {
"en-US": {
contentType: "image/png",
fileName: "Sample_45.png",
uploadFrom: {
sys: {
linkType: "Upload",
type: "Link",
id:uploadId
}
}
}
}
}
};
return axios
.put(
"https://api.contentful.com/spaces/" +
space_id +
"/assets/" +
assetId +
"/files/en-US/process",
asset.data.fields,
config
)
After that I can see an asset in Contentful Media, but the image never really loads, nor the image size is displayed. It seems like some how Contenful does not recognize the file, or has been incorrectly associated with the asset; I have no clue. Help please.
Looks like you are using React.
Create an upload form :
<input type="file" onChange={this.fileChangedHandler}>
<button onClick={this.uploadHandler}>Upload!</button>
and set your state, fileChangedHandler, and uploadHandler:
state = {selectedFile: null}
fileChangedHandler = (event) => {
this.setState({selectedFile: event.target.files[0]})
}
uploadHandler = () => {
axios.post(
'https://upload.contentful.com/spaces/{space_id}/uploads,
this.state.selectedFile,
config
)
}
And once the upload is finished, you can create, process, and publish the asset.
After i click on Personal Image, an Sweetalert appear.
I want to upload image from input Swal() sweetAlert, but I always received null File in ActionResult.
I check it with a formData Send and never got actionresult request.
I working in MVC5 if someone can help me!! Thanks!!
Excuse me for my english.
Controller:
[LogActionFilter]
[HttpPost]
[ValidateAntiForgeryToken]
[MenuPermissions]
public ActionResult EditImage(HttpPostedFileBase inputImage)
{
//if (Request.Files.Count <= 0)
// return Json(new Dictionary<string, string>() { { "error", "Problemas en el servidor." } });
//var avatar = Request.Files[0];
var avatar = inputImage;
var userName = User.Identity.GetUserName();
if (Directory.Exists(Server.MapPath("~/Uploads/UserImg/")) == false)
{
Directory.CreateDirectory(Server.MapPath("~/Uploads/UserImg/"));
}
var path = Server.MapPath("~/Uploads/UserImg/" + userName + ".jpg");
avatar?.SaveAs(path);
return Json(new Dictionary<string, string>() { { "success", "Datos del usuario modificados satisfactoriamente." } });
}
View: Javascript
$("#AvatarId").click(function (eve) {
swal({
title: 'Selecciona tu imagen',
input: 'file',
inputAttributes: {
'accept': 'image/*',
'aria-label': 'Carga tu imagen de perfil',
'id': 'inputImage'
}
}).then(function (file) {
/*Ajax*/
var token = $('[name=__RequestVerificationToken]').val();
var Datos = {
__RequestVerificationToken: token,
Imagen: file
}
$.ajax({
url: "#Url.Action("EditImage", "Account")",
type: 'POST',
data: Datos,
success: function (data) {
if (data['success']) {
//var result = e.target.result;
//$('#AvatarIconId').attr("src", result);
swal("Lolazo","Hahaha","success");
} else {
var message = document.createTextNode(data['error']);
var p = $('#genericError')
p.empty();
p.append(message);
}
},error: function () {
var message = document.createTextNode('¡Ocurrió un error inesperado! Comuniquese con el proveedor del sistema.');
var p = $('#genericError')
p.empty();
p.append(message);
}
});
Getting this error while choosing image file
import {Injectable} from '#angular/core';
#Injectable()
export class UploadPhotoService {
filesToUpload: Array<File>;
constructor() {
this.filesToUpload = [];
}
upload() {
this.makeFileRequest("rest/api/upload", [], this.filesToUpload).then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}
fileChangeEvent(fileInput: any){
this.filesToUpload = <Array<File>> fileInput.target.files;
}
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert("Upload successful!");
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("token"));
xhr.send(formData);
});
}
}
<div class="field">
<label>Upload Photo</label>
<input type="file" (change)="uploadPhotoService.fileChangeEvent($event)" />
<button type="button" (click)="uploadPhotoService.upload()" class="ui mini button">Upload</button>
</div>
After choosing image file it showing the above error , Is there any other way to upload image file in angular2.. Please help on that too, and its giving EXCEPTION: Error in ./AddAdvertComponent class AddAdvertComponent - inline template:30:2 caused by: Cannot read property 'fileChangeEvent' of undefined
ORIGINAL EXCEPTION: Cannot read property 'fileChangeEvent' of undefined
throwing error
ORIGINAL EXCEPTION: Cannot read property 'fileChangeEvent' of undefined
because you are calling fileChangeEvent not correctly or your uploadPhotoService have not definer, you have to call it like this
if the method is in the same class
<input type="file" (change)="fileChangeEvent($event)" />
or if your method is in some different class or in some service than make sure you initilize that service in the constructor like this
constructor(prive uploadPhotoService: UploadPhotoService) { }
than you are able to use like this
<input type="file" (change)="uploadPhotoService.fileChangeEvent($event)" />