Upload data and image base 64 to rest server as truncated - image

I'm using advanced rest console of chrome and i'm sending a rest request to a server that saves an image to database.
below the header data and the body of the request:
Header:
Content-Type: image/jpg; charset=UTF-8
Body:
device_id=1442045686166&id_utente=1&id_attivita=-1&id_prodotto=115&file=/9j/4AAQSkZJRgABAQAAAQABAAD/...
the server, not mine, it all comes back ok but here is the result
image returned
The other images were uploaded from Android application that sends requests to the same server!
The server is a java web application deployed on jboss application server.
This is the html part of retrive image:
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<label for="exampleInputEmail1">Immagine</label>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="thumbnail">
<i ng-hide="imageSrc">Nessuna immagine selezionata</i>
<img ng-hide="!imageSrc" ng-src="{{imageSrc}}" on-error-src="images/noimg.png" spinner-on-load/>
<div class="caption">
<div class="form-group">
<input type="file" id="imageInputFile" name="imageInputFile" ng-model="imageInputFile" ng-change="uploadFile(this)" ng-file-select="onFileSelect($files)" base-sixty-four-input maxsize="500" accept="image/*">
<p class="help-block">Scegli un'immagine in locale.</p>
</div>
</div>
</div>
</div>
</div>
</div>
And this is the angularjs code:
$scope.uploadImage = function (id_prodotto) {
trace("uploadImage, inizio");
var img64 = $scope.imageSrc.replace(/^data:image\/(png|jpeg);base64,/, "");
$scope.bodyRawImg =
'device_id=' + $scope.key +
'&id_utente=' + $scope.BeanUtente[0].id_utente +
'&id_attivita=' + $scope.BeanUtente[0].id_attivita +
'&id_prodotto=' + id_prodotto +
'&file=' + img64;
trace("uploadImage, $scope.bodyRawImg " + $scope.bodyRawImg);
$http({
method: 'POST',
url: ($location.absUrl().split("/easyMenu/"))[0] + '/app/file/uploadFoto',
async: false,
processData: false,
headers: {
'Content-Type': 'image/jpg'
},
data: $scope.bodyRawImg,
})
.success(function (data, status, headers, config) { // success
trace("uploadImage, success");
$scope.result = (data || []);
trace("uploadImage response: " + JSON.stringify($scope.result));
})
.error(function (data, status, headers, config) { // error
trace("uploadImage, error");
});
$scope.cambioImmagine = false;

Related

I am trying to show data in summer note using ajax

I am trying to show data in summer note from ajax request but unfortunately it's not showing on summer note please help me how can i resolve that ? thank u.
html view
<div class="form-outline">
<div class="form-outline mb-2">
<textarea class="summernote" id="description" name="description"
height="200px" required></textarea>
</div>
</div>
ajax script
$(document).on('click','.editBtn',function(){
var notificationId = $(this).data("id");
$("#editModel").modal('show');
var url = "{{URL('/notification/edit/')}}";
$.ajax({
type:"GET",
url: url + '/' + notificationId,
dataType:'JSON',
success:function (response){
console.log(response);
$('#description').val(response.description);
}
});
});

How to update data on a page using ajax script?

There is a script that needs to update the data on the page in a specific div. But instead of updating, the block with the div is simply hidden and in order for it to appear again, you need to reload the page. The data comes in data, but here is $ ("# userPost" + id) .html (data); something doesn't work.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
// var formData = $('#EditPostForm'+id).serialize();
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "POST",
data: formData,
success: function(data) {
console.log(data);
$("#userPost"+id).html(data);
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
processData: false,
contentType: false,
});
});
And div
<div id="userPost{{$post->id}}">
#if($post->img)
<div>
<img src="{{$post->img}}" class="img-fluid">
</div>
#endif
<br>
#if($post->title)
<div class=" mr-1 mb-3 titleleft">
<h5 style="color: black"><b>{{$post->title}}</b></h5>
</div>
#endif
#if($post->message)
<div class="text-muted text-small margins" style="white-space: pre-wrap;">{{mb_strimwidth($post->message, 0, 600, " . . . Read more")}}</div>
#endif
#if($post->videoPost)
<div class="embed-responsive embed-responsive-16by9 mt-4 mb-2">
<iframe class="embed-responsive-item" src="{{$post->videoPost}}" allowfullscreen></iframe>
</div>
#endif
</div>
Try doing this way:
$("#userPost"+id).load(url);
or
$("#userPost"+id).html(data).load(url);

Ajax request for delete image doesnt work in laravel

I want to delete the image in the preview box, as well as delete it in the database using ajax. Deleting the image in the preview box was successful, but deleting it from the database didn't work.
here my ajax:
$(document).ready(function() {
document.getElementById('pro-image').addEventListener('change', readImage, false);
$(".preview-images-zone").sortable();
$(document).on('click', '.image-cancel', function() {
let no = $(this).data('no');
let idData = $(this).data('id');
$(".preview-image.preview-show-" + no).remove();
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}',
data: {
'id': idData
},
success: function(data) {
alert('success');
}
});
});
});
My Html:
<!-- Percobaan Preview -->
<fieldset class="form-group">
<div class="offset-md-2 col-md-6">
Upload Gambar
<input type="file" id="pro-image" name="gambarku[]" style="display: none;" class="form-control" multiple>
</div>
</fieldset>
<div class="preview-images-zone offset-md-2 col-md-8">
<!-- Gambar Utama -->
<div class="preview-image preview-show-1">
<div class="image-cancel" data-no="1">x</div>
<div class="image-zone"><img id="pro-img-1" src="{{asset('storage/rumah/'.$rumahku->gambar_rumah)}}"></div>
</div>
<!-- Gambar Tambahan -->
<?php $counter = 2 ?>
#foreach($rumahku->gambar as $rows)
<div class="preview-image preview-show-{{$counter}}">
<div class="image-cancel" data-no="{{$counter}}" data-id="{{$rows->id_gambar}}">x</div>
<div class="image-zone"><img id="pro-img-{{$counter}}" src="{{asset('storage/rumah/'.$rows->gambar_unit)}}"></div>
</div>
<?php $counter++ ?>
#endforeach
</div>
<!-- /preview -->
my route
Route::post('unit/API/simpan/{id}', 'partner\UnitController#simpanGambar');
my controller
public function simpanGambar($id)
{
$gambar = Gambar::find($id);
$gambar->delete();
}
you can try this
Route::post('unit/API/simpan', 'partner\UnitController#simpanGambar');
and
public function simpanGambar(Request $request)
{
$gambar = Gambar::find($request->id);
$gambar->delete();
}
or in ajax
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}' +'/'+ id, <---------- pass id here

Django Python can not upload directory with large quantity of files

I am trying to upload a directory with large number of dicom files using Django and JQuery ajax. Each file size is not more than 600kb. I can upload 200 files at a time. If I increase the number of files (tried to upload 14000 files), it doesn’t work. The site gets stuck and it’s not showing any error. Can anyone please help me with this problem? I have attached my code below. Thanks in advance.
View.py:
def handle_uploaded_file(f,filePath):
with open(filePath+'/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def UploadScanView(request):
if request.method == 'POST':
form = create_scan_form(request.POST)
if form.is_valid():
scan = form.save(commit=False)
scan.project_id = form.cleaned_data.get('project_id')
directory_name = request.POST.get('directories')
json_to_dictionary = json.loads(directory_name)
print(json_to_dictionary)
for upload_file in request.FILES.getlist('file'):
file_path = settings.MEDIA_ROOT+'/'+os.path.dirname(json_to_dictionary[upload_file.name])
print(file_path)
if os.path.exists(file_path):
handle_uploaded_file(upload_file, file_path)
else:
os.makedirs(file_path)
handle_uploaded_file(upload_file,file_path)
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
else:
form = create_scan_form()
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
HTML and JQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
/*fileupload div*/
$(document).ready(function(){
$("#my-file").on('change',function(e){ //submit(function(e){
$("#file-wrap p").text('Now click on Upload button');
});
$("#my-form").on('submit',function(e){ //submit(function(e){
files = document.querySelector("#my-file").files;
var directories = {}
for (var file of files) {
file.webkitRelativePath
directories[file.name] = file.webkitRelativePath
}
directories = JSON.stringify(directories);
document.querySelector("#directories").value = directories
var eventType = $(this).attr("method"); // get method type for #my-form
var eventLink = $(this).attr("action"); // get action link for #my-form
//alert(directories);
//////
var formData = new FormData(this);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
headers: { "X-CSRFToken": '{{ csrf_token }}' },
type: eventType,
url: eventLink,
//data: new FormData(this), // IMPORTANt
data: formData,
cache: false,
contentType: false,
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
var percentComplete = e.loaded / e.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function(getResult) {
$('#my-form')[0].reset(); // reset form
$("#file-wrap p").html('Drag and drop file here'); // change wrap message
}
});
e.preventDefault();
});
});
/*fileupload div*/
</script>
<form id="my-form" method="POST" action="{% url 'fileupload:upload_scan' %}" enctype="multipart/form-data"> <!--independentSub-->
{% csrf_token %}
<div id="user_form" class="container">
<div class="form-group col-sm-4" id="project_id">
{{ form.project_id|as_crispy_field }}
</div>
<!--fileupload div-->
<div id="independentSubDiv" class="row">
<div id="file-wrap" class="form-group col-sm-6" >
<p>Drag and drop file here</p>
<input id="my-file" type="file" name="file" multiple webkitdirectory directory draggable="true">
<input type="text" id="directories" name="directories" hidden />
</div>
</div>
<div style="padding-left: initial" id="independentSubDiv" class="form-group col-sm-7" >
<button type="submit" class="btn btn-primary btn-lg btn-block" name="submit_btn" id="submit_btn">Submit</button>
</div>
<div class="progress form-group col-sm-7" style="padding-left: initial" id="progressDiv" >
<div class="progress-bar progress-bar-success myprogress " role="progressbar">0%</div>
</div>
</div>
</form>

Cakephp FormData Ajax file upload

I'm stuck in uploading from data and file using FormData + Ajax + CakePHP
Here is my form:
<form name="multiform" class="frmaddproduct" action="addproduct" method="POST" enctype="multipart/form-data">
<div class="formrow">
<div class="createproductlabel leftfloat">Name</div>
<div class="formcontrol leftfloat"><input type="text" name="name"/><br/><span>Name?</span></div>
<div class="clear"></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat">Cost</div>
<div class="formcontrol leftfloat"><input type="text" name="cost"/></div>
<div class="clear"></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat">Discount</div>
<div class="formcontrol leftfloat"><input type="text" name="discount" class="discount" maxlength="5"/> %</div>
<div class="clear"></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat">Description</div>
<div class="formcontrol leftfloat"><textarea name="description" rows="5"></textarea></div>
<div class="clear"></div>
</div>
<div class='formrow'>
<div class='createproductlabel leftfloat'>Choose file</div>
<div class='formcontrol leftfloat'><input type='file' name=''productpicture'/></div>
<div class='closephotos leftfloat'><img src='../img/close.png' class='closeproductpicture'/></div>
<div class='clear'></div>
</div>
<div class="formrow">
<div class="createproductlabel leftfloat"> </div>
<div class="formcontrol leftfloat"><input type="button" name="btncreateproduct" value=" Create Product "/></div>
<div class="clear"></div>
</div>
</form>
Here is my code for submitting this form:
$(".frmaddproduct").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
if(window.FormData !== undefined) // for HTML5 browsers
{
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
}
else // for older browsers
{
// generate a random id
var iframeId = 'unique' + (new Date().getTime());
// create an empty iframe
var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');
// hide it
iframe.hide();
// set form target to iframe
formObj.attr('target',iframeId);
// Add iframe to body
iframe.appendTo('body');
iframe.load(function(e)
{
var doc = getDoc(iframe[0]);
var docRoot = doc.body ? doc.body : doc.documentElement;
var data = docRoot.innerHTML;
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
});
}
});
In firebug, I can see data being sent:
-----------------------------2463414040929 Content-Disposition: form-data; name="categoryproduct" 1 -----------------------------2463414040929 Content-Disposition: form-data;
name="companyproduct" 1 -----------------------------2463414040929 Content-Disposition: form-data;
name="name" AAA -----------------------------2463414040929 Content-Disposition: form-data; name="cost" 34
But when I try to read or dump request data in Controller, I get: Array()
i.e. No data being sent
debug($this->request->data);
also, $this->log($this->request->data["discount"]) gives me blank value
Please help me out on this.
I'm confused where I'm getting it wrong
I didn't used cakephp form helpers to create form
USE the regular $_FILES PHP Server variable

Resources