I have a form with a file upload field and a hidden field to store the uploaded file name as follows:
<form enctype="multipart/form-data" action="http://localhost:8000/create" method="POST">
// other form fields
<input id="img_logo" type="hidden" value="" name="img_logo">
<input type="file" name="file" id="file" class="inputfile"/>
<label for="file" class="btn btn-primary" >Upload</label>
<div id="img-thumb"></div>
<input type="submit" value="Submit">
</form>
My ajax file upload method populates the filename of the hidden img_logo field as follows after a successful upload:
this.on("success", function(file, response) {
$('input[name="img_logo"]').val(response.file);
$("#img-thumb").html("<img src='/img/tmp/"+response.file+"' />");
}
This is the upload method which gets called when a file is uploaded
public function upload(Request $request) {
if($request->hasFile('file')) {
//upload an image to the /img/tmp directory and return the filepath.
$file = $request->file('file');
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$tmpFilePath = '/img/tmp/';
Image::make($file->getRealPath())->resize(360, 180)->save(public_path($tmpFilePath) . $tmpFileName);
return response()->json([
'success' => true,
'file' => $tmpFileName
] , 200);
}
else {
return response()->json(false, 200);
}
}
When I submit the form I want to move the image from img/tmp directory to img/logos directory and rename the file by prefixing the article id. I can determine if a file has been uploaded by checking the img_logo hidden input value as follows:
Public function create(Request $request)
{
$article = Article::create($request->all());
if ($request->has('img_logo')) {
// How do i copy the file from img/tmp to img/logos with new name
$fileName = $article->id . '-' . Request::input('img_logo');
$article->img_logo = $fileName;
$article->save();
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire