Summernote - Image url instead of Base64 Laravel - file-upload

I'm trying to upload image by summernote editor. But There is an issues,
Script to change base64 to img url:
$(document).ready(function () {
$('#long_desc').summernote({
height: 200, // set editor height
minHeight: null, // set minimum height of editor
maxHeight: null, // set maximum height of editor
focus: true,
callbacks: {
onImageUpload: function (files) {
sendFile(files[0], 'long_desc')
},
},
})
function sendFile(file, editor) {
data = new FormData()
data.append('file', file)
$.ajax({
data: data,
type: 'POST',
url:'/dashboard/portfolio/add-portfolio',
cache: false,
contentType: false,
processData: false,
success: function (url) {
$('#'+editor).summernote('insertImage', url, 'filename')
},
error:function(){
console.log("Error")
}
})
}
})
But in the script the url is:->>>>> url:'/dashboard/portfolio/add-portfolio',
The error is as follows->>
In this case, I need to save the image first and return the url to this ajax method url. In laravel 8 How can I save image url and return that url for this ajax method. It is also noted that I', am using summernote editor for this task.
From this summernote editor, I want to save image by img upload as follows:
Help me giving a proper solution.

Related

Uploading large video files on background in react native

I need to upload large video files in the background.
What is the best way to achieve this?
I tried using this library (react-native-background-upload). But the problem is, I can't send any other data along with the video file. The API expects the following data:
{
projectId: number,
title: string,
video: file,
};
This is the piece of code to send the files with multipart using the library:
const options = {
url: url,
path: pathToVideoFile,
method: 'POST',
field: 'video',
type: 'multipart',
};
Are there any alternatives that I can use? Can react-native-background-fetch be used for this use case?
in react-native-background-upload
you can use parameters in options to send additional data
Additional form fields to include in the HTTP request. Only used when type: 'multipart
const options = {
url: url,
path: pathToVideoFile,
method: 'POST',
field: 'video',
type: 'multipart',
parameters : {
key1: "value1",
key2: "value2",
}
};
you can see all options params here here
you can install react-native-compressor package which is made by me
Installation
yarn add react-native-compressor
Usage
import {Video} from 'react-native-compressor';
const headers={
'Content-Type': '',
}
const uploadResult = await Video.backgroundUpload(
"http://w.hbu50.com:8080/hello.mp4",
fileUri,
{httpMethod: 'PUT', headers},
(written, total) => {
onProgress({
status: 'uploading',
progress: written / total,
uploading: true,
});
},
);

How to display a PDF generated with express/pdfkit in browser from api-endpoint

I generate a pdf with with express and pdfkit like:
router.get("/create_pdf", (req, res) => {
var foo = req.body.foo;
var bar = req.body.bar;
// query Postgres with foo and bar to get some custom values
//create pdf
const doc = new PDFDocument();
doc.pipe(res);
doc.fontSize(25).text("Just a header", 100, 80);
// build some more stuff depending of Postgres query
doc.end();
})
My frontend using vue receives the response
print: function() {
data = {foo: "foo", bar: "bar"};
this.axios({
method: "get",
url: "get_recipe_as_pdf",
data: data,
})
.then((response) => {
console.log(response);
window.open(response.data);
})
.catch(() => {
//some error
});
},
The console shows data: "%PDF-1.3↵%����↵7 0 obj↵<...
window.open(...) opens a blank tab.
I found similar questions but could not find an answer. I probably have some understanding problems, so I'd appreciate a hint. Thanks.
In your express app: res.setHeader('Content-Type', 'application/pdf');
In your frontend just open the link "manually" like clicking on an anchor: click me
The pdf should open in a new tab if your browser supports that, else it will be downloaded.
Edit: for clarification: window.open expects a url as first parameter, not the content of a pdf.

Having issues uploading images using form data and fetch

I have a React Native application that is using fetch to upload some text data and images. We recently noticed not all the images are saving on the server. Firing up Charles I found some of the images look malformed, not sure exactly why or what is causing this.
Through testing I have tried different images, the same image, etc and still seem to have this issue. In the screenshot below you can see the request and how only one image has the correct data. Im not sure what those symbols mean or why they are there..
As you can see in the code, I am appending both images the same exact way..
// data is my object that contains job info, image meta info, etc..
const formData = new FormData();
formData.append("sc", JSON.stringify(data));
// append call images
data.SavedImages.forEach(image => {
if (image.meta && image.meta.uri) {
formData.append(`image_sc_${image.ImageID}`, {
uri: image.meta.uri,
type: "image/jpeg",
name: data.CallID
});
}
});
//append equip images
data.Equip.forEach(e => {
e.SavedImages.forEach(image => {
if (image.meta && image.meta.uri) {
formData.append(`image_equip_${image.ImageID}`, {
uri: image.meta.uri,
type: "image/jpeg",
name: image.EquipmentID
});
}
});
});
return fetch(Api.buildURL("ServiceCallPayload"), {
method: "POST",
body: formData
})
I would expect the images to both be included in the request and in the correct format but instead its corrupted somehow.
Colleague of mine figured it out, the name property needed to have the proper file extension, otherwise it was treated as text.
// append call images
data.SavedImages.forEach(image => {
if (image.meta && image.meta.uri) {
formData.append(`image_sc_${image.ImageID}`, {
uri: image.meta.uri,
type: "image/jpeg",
name: data.CallID + '.jpeg'
});
}
});

How to find/replace specific object in Vuex?

I have simple image upload via action and mutation. The main thing is that I firstly want to store preloader and then, when the image is uploaded to the server show the image and remove preloader.
export default new Vuex.Store({
state: {
images: [],
},
mutations: {
addImage(state, image) {
state.images.push(image);
}
},
actions: {
saveImage({commit}, image) {
commit('addImage', {url: 'http://via.placeholder.com/100x100?text=loading...'});
let form_data = new FormData();
form_data.append('file', image);
return new Promise((resolve, reject) => {
jQuery.ajax({
url : '/api/v1/products/files/save',
data : form_data,
type : 'POST',
cache: false,
contentType: false,
processData: false,
success: response => {
// commit('addImage', response.file);
// here I somehow need to replace/readd the response.file
resolve(response.file)
}
}).fail(() => reject())
})
}
},
strict: debug
})
I basically could use array.find method to look for url:http://via.placeholder.com/100x100?text=loading... remove it and then add new one but not sure if it's is the right method...
You give vuex action too much to do. Let it do one single task - upload the file. The placeholder/preloader should be handled by the component even without a vuex state. All the component needs to know is whether the image is uploading or not in order to show the loading indicator. Since your action returns a Promise your component will know when it's ready.

Why success callback is not called in extjs form submission?

I'm trying to upload a file using Ext JS forms and in case of success or failure, show appropriate messages. But I'm not able to get the desired result. I'm not able to make success or failure callbacks work in form.submit action.
What I've done till now is:
Creating a form with this script:
new Ext.FormPanel({
fileUpload: true,
frame: true,
url: '/profiler/certificate/update',
success: function() {
console.log(arguments);
},
failure: function() {
console.log(arguments);
}
}).getForm().submit()
​/*
The response Content-Type is text/html (with charcode=utf8);
The response JSON is: { "success": true }
*/​​
Setting the response Content-Type to text/html based on this answer.
Sending an appropriate JSON result back, based on Ext JS docs. The response captured via Fiddler is:
{"success":false}
or
{"success":true}
I even set the response Content-Type to application/json. But still no success.
I've read links like this and this, but none of them helped. Please note that I also tried another script which creates a form, with an upload field in it, and a save button, and I submitted the form in the handler of the save button. But still no callback is fired.
Here's a working example - Javascript code:
Ext.onReady(function () {
Ext.define('ImagePanel', {
extend: 'Ext.form.Panel',
fileUpload: true,
title: 'Upload Panel',
width: 300,
height: 100,
onUpload: function () {
this.getForm().submit({
url: 'upload.php',
scope: this,
success: function (formPanel, action) {
var data = Ext.decode(action.response.responseText);
alert("Success: " + data.msg);
},
failure: function (formPanel, action) {
var data = Ext.decode(action.response.responseText);
alert("Failure: " + data.msg);
}
});
},
initComponent: function () {
var config = {
items: [
{
xtype: 'fileuploadfield',
buttonText: 'Upload',
name: 'uploadedFile',
listeners: {
'change': {
scope: this,
fn: function (field, e) {
this.onUpload();
}
}
}
}
]
};
Ext.apply(this, Ext.apply(this.initialConfig, config));
this.callParent(arguments);
}
});
var panel = Ext.create('ImagePanel', {
renderTo: Ext.getBody()
});
});
And PHP code:
<?php
if (isset($_FILES)) {
$temp_file_name = $_FILES['uploadedFile']['tmp_name'];
$original_file_name = $_FILES['uploadedFile']['name'];
echo '{"success": true, "msg": "'.$original_file_name.'"}';
} else {
echo '{"success": false, "msg": "No Files"}';
}
I have been struggling with this for quite some time now as well. Here's my code:
Ext.getCmp('media-upload-form').getForm().doAction('submit', {
url: './services/recordmedia/upload',
method: 'post',
waitMsg: 'Please wait...',
params: {
entityId: this.entityId,
},
failure: function(form, action){
alert(_('Error uploading file'));
this.fireEvent('file-upload');
this.close();
},
success: function(form, action){
this.fireEvent('file-upload');
this.close();
},
scope: this
})
The response was always wrapped in <pre> tags by the browser, what caused the Extj lib not to call the callbacks. To fix this:
make sure your server returns the correct json: {"success":true}
make sure that the content-type is set to text/html
Actually, this is well covered by docs for Ext.form.Panel and Ext.form.Basic. The problem with your code not working is that there are no config options "success", "failure" for the form panel. You should put them in the config object passed to the submit action. So your code should look like:
new Ext.FormPanel({
fileUpload: true,
frame: true
}).getForm().submit({
url: '/profiler/certificate/update',
success: function() {
console.log(arguments);
},
failure: function() {
console.log(arguments);
}
});
Note the difference: In Ext 4, there is a form component (Ext.form.Panel) which is basically a view component concerned with how you form looks, and then there is the underlying form class (e.g. Ext.form.Basic) concerned with the functionality. Form submissions are handled by Ext.form.Basic (or whatever returned by your form.getForm()).