file name automatically change when i upload the file - file-upload

I'm new to CodeIgniter and having the following issue. When I upload a file, its successfully uploaded on my local folder and the file name saved to the db. The problem is, file name has been changed after uploading.
eg:
file name "screenshot image 123.png" -> "screenshot_image_123.png"
It just convert the space into underscore;this issue occurred only when the file name having space.Other than this issue all the other files uploading successfully. Given below is my code which I used on my controller page:
public function upload_pic()
{
$image_path = realpath(APPPATH . '../uploads');
$config['upload_path'] = $image_path;
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['file_name'] = $_FILES['file']['name'];
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('file'))
{
echo $this->upload->display_errors();
}
else
{
$finfo=$this->upload->data();
$data['uploadInfo'] = $finfo;
}
}
Can anyone help me????

Try before saving file name generate some unique
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$filename = sha1_file($filename). md5(date('Y-m-d H:i:s:u')) . '.'. $ext; //not only this you can generate any format
$config['file_name'] = $filename; //Use this file name is db too

Related

laravel 7 pdf-to-text | Could not read pdf file

I installed this laravel package to convert pdf file into text. https://github.com/spatie/pdf-to-text
I'm getting this error:
Could not read sample_1610656868.pdf
I tried passing the file statically by putting it in public folder and by giving path of uploaded file.
Here's my controller:
public function pdftotext(Request $request)
{
if($request->hasFile('file'))
{
// Get the file with extension
$filenameWithExt = $request->file('file')->getClientOriginalName();
//Get the file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//Get the ext
$extension = $request->file('file')->getClientOriginalExtension();
//File name to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload File
$path = $request->file('file')->storeAS('public/ebutifier/pdf', $fileNameToStore);
}
// dd($path);
$location = public_path($path);
// $pdf = $request->input('file');
// dd($location);
// echo Pdf::getText($location, 'usr/bin/pdftotext');
$text = (new Pdf('public/ebutifier/pdf/'))
->setPdf($fileNameToStore)
->text();
return $text;
}
Not sure why it's not working any help would be appreciated.
You used spatie/pdf-to-text Package.
I also tried to use this package but it gave me this kind of error.
So, I used asika/pdf2text package and it worked properly
Asika/pdf2text pacakge
And this is my code
$path = public_path('/uploads/documents/'. $file_name);
$reader = new \Asika\Pdf2text;
$output = $reader->decode($path);
dd($output);
Hopefully, it will be helpful for you.

Yii2 - rename file on upload if the file with the same name exist

How can I rename file if the file with the same name exist (prevent overwrite)? This method is used for uploading file:
// Upload user avatar
public function upload()
{
if ($this->validate()):
$this->avatar->saveAs('../web/images/avatars/' . $this->avatar->baseName . '.' . $this->avatar->extension);
return true;
endif;
return false;
}
Test if file exists with php function and then assign a proper name to your file:
$cnt = 1;
while (file_exists(string $filename)) {
$filename = $this->avatar->basename . $cnt;
$cnt++;
}
Then save.

Uploading file to Server using JSP

i was searching for a way to upload a file to server and found the following code ..
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("/user2/tst/test"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}else{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
this code is working perfectly fine .. the only problem i am facing is , the file that is updated is getting stored in apache/bin folder ..
for this it was specified to add the following code to web.xml that is available in ROOT/WEB-INF
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
/user2/tst
</param-value>
</context-param>
even after this the file is getting stored in bin folder ..
i needed some help in this regard .. thanks in advance ..

ASP MVC 2 Uploading file to database (blob)

I am trying to upload a file via a form and then save in in SQL as a blob.
I already have my form working fine, my database is fully able to take the blob and I have a controller that take the file, saves it in a local directory:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(int id, HttpPostedFileBase uploadFile)
{
//allowed types
string typesNonFormatted = "text/plain,application/msword,application/pdf,image/jpeg,image/png,image/gif";
string[] types = typesNonFormatted.Split(',');
//
//Starting security check
//checking file size
if (uploadFile.ContentLength == 0 && uploadFile.ContentLength > 10000000)
ViewData["StatusMsg"] = "Could not upload: File too big (max size 10mb) or error while transfering the file.";
//checking file type
else if(types.Contains(uploadFile.ContentType) == false)
ViewData["StatusMsg"] = "Could not upload: Illigal file type!<br/> Allowed types: images, Ms Word documents, PDF, plain text files.";
//Passed all security checks
else
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName)); //generating path
uploadFile.SaveAs(filePath); //saving file to final destination
ViewData["StatusMsg"] = "Uploaded: " + uploadFile.FileName + " (" + Convert.ToDecimal(uploadFile.ContentLength) / 1000 + " kb)";
//saving file to database
//
//MISSING
}
return View("FileUpload", null);
}
Now all I am missing is putting the file in the database. I could not find anything on the subject... I found some way to do it in a regular website but nothing in MVC2.
Any kind of help would be welcome!
Thank you.
This could help: http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/
Since you have HttpPostedFileBase in your controllers method, all you need to do is:
int length = uploadFile.ContentLength;
byte[] tempImage = new byte[length];
myDBObject.ContentType = uploadFile.ContentType;
uploadFile.InputStream.Read(tempImage, 0, length);
myDBObject.ActualImage = tempImage ;
HttpPostedFileBase has a InputStream property
Hope this helps.
Alright thanks to kheit, I finaly got it working. Here's the final solution, it might help someone out there.
This script method takes all the file from a directory and upload them to the database:
//upload all file from a directory to the database as blob
public void UploadFilesToDB(long UniqueId)
{
//directory path
string fileUnformatedPath = "../Uploads/" + UniqueId; //setting final path with unique id
//getting all files in directory ( if any)
string[] FileList = System.IO.Directory.GetFiles(HttpContext.Server.MapPath(fileUnformatedPath));
//for each file in direcotry
foreach (var file in FileList)
{
//extracting file from directory
System.IO.FileStream CurFile = System.IO.File.Open(file, System.IO.FileMode.Open);
long fileLenght = CurFile.Length;
//converting file to a byte array (byte[])
byte[] tempFile = new byte[fileLenght];
CurFile.Read(tempFile, 0, Convert.ToInt32(fileLenght));
//creating new attachment
IW_Attachment CurAttachment = new IW_Attachment();
CurAttachment.attachment_blob = tempFile; //setting actual file
string[] filedirlist = CurFile.Name.Split('\\');//setting file name
CurAttachment.attachment_name = filedirlist.ElementAt(filedirlist.Count() - 1);//setting file name
//uploadind attachment to database
SubmissionRepository.CreateAttachment(CurAttachment);
//deleting current file fromd directory
CurFile.Flush();
System.IO.File.Delete(file);
CurFile.Close();
}
//deleting directory , it should be empty by now
System.IO.Directory.Delete(HttpContext.Server.MapPath(fileUnformatedPath));
}
(By the way IW_Attachment is the name of one of my database table)

My file isn't being moved to the specified and newly created folder using mkdir

So I'm having an issue. When someone signs up for an account on the site I'm building, they go to a setup page where they can upload a profile picture. I'm using mkdir to auto create a sub-folder with their username which is working fine, and CHMOD is 777 on that sub folder. The problem I'm having is that image is not being moved to that specified sub-folder, but it's going into the "uploads" folder which is it's parent directory.
Hopefully I haven't confused anyone, but I'm really needing help.
Below is my script I wrote to do this.
===============================================================================
require_once('../admin/includes/config.php');
$uploaded_file = $_REQUEST['uploaded_file'];
$member_id = $_REQUEST['member_id'];
$name = $_REQUEST['name'];
$location = $_REQUEST['location'];
$hobbies = $_REQUEST['hobbies'];
$hobby = $_REQUEST['hobby'];
// using member_id, extract the username from the members table so we can auto create a sub-directory for the images
$result = mysql_query("SELECT username FROM members WHERE member_id = '$member_id'");
while($row = mysql_fetch_array($result))
{
$username = $row['username'];
}
// unmask to change CHMOD of newly created sub directory to 777
$old_mask = umask(0);
//Create directory with member's username
$madedir = mkdir('../admin/uploads/'.$username.'', 0777) /*== TRUE ? 1 : 0*/;
umask($old_mask);
// Assign the directory the file is going to be uploaded to
$uploaddir = '../admin/uploads/'.$username.'';
// Get the file name
$file_name = $_FILES['uploaded_file']['name'];
// Upload file to assigned directory with file name
$uploadfile = $uploaddir . basename($_FILES['uploaded_file']['name']);
// If the file has been uploaded, run this script
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile)) {
echo "Success";
} // end if
else {
echo "there was an error uploading your file";
}
You seem to be missing a / at the end of the upload directory. Change this:
$uploaddir = '../admin/uploads/'.$username.'';
to this:
$uploaddir = '../admin/uploads/'.$username.'/';