Jul 27, 2016
0
Level 3
Get Value From Javascript
Hi I am using `dropdown.js' to upload image to a user profile image.
I need to get the image's path I have uploaded, then pass it to laravel and insert it to the current user image_path column record.
Controller:
public function index()
{
return view('dropzone_demo');
}
public function uploadFiles()
{
$message="Profile Image Created";
$input = Input::all();
$rules = array(
'file' => 'image|max:3000',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Response::make($validation->errors->first(), 400);
}
$destinationPath = 'uploads'; // upload path: public/uploads
$extension = Input::file('file')->getClientOriginalExtension(); // getting file extension
$fileName = mt_rand(11111, 99999) . '.' . $extension; // renameing image
$upload_success = Input::file('file')->move($destinationPath, $fileName); // uploading file to given path
if ($upload_success) {
return Response::json('success', 200);
} else {
return Response::json('error', 400);
}
}
View:
<div class="container">
<div class="dropzone" id="dropzoneFileUpload">
</div>
<button type="button" id="uploadPhoto">Upload Photo</button>
</div>
<script type="text/javascript">
// Since we're using Juery to initialize Dropzone, we Set autoDiscover to false,so that dropzone object is not initialized twice.
// So we only initialize it here: var myDropzone
Dropzone.autoDiscover = false;
// dropzone should load when the DOM is completely loaded
jQuery(document).ready(function(){
var myDropzone = new Dropzone("div#dropzoneFileUpload", {
url: "{{action('DropzoneController@uploadFiles')}}",
maxFilesize: 2, // MB
maxFiles: 1,
addRemoveLinks: true,
autoProcessQueue:false,
params: {
_token: "{{csrf_token()}}"
},
});
myDropzone.on("success", function(file,resp){
if(resp=="success"){
alert("Image uploaded successfully");
}
else {
alert("Faild to upload image! Try again");
}
});
jQuery("button#uploadPhoto").click(function(){
myDropzone.processQueue();
});
});
</script>
profile image model:
class profile_image extends Model
{
protected $table="profile_images";
public function user()
{
return $this->belongsTo('App\User');
}
also added the inverse in the User model.
Thanks.
Please or to participate in this conversation.