Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the helper Path to get the routes to my file.

function upload_file() {

    //$this->load->helper('path');
    //$path = set_realpath('./uploads/');

    //upload file

    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = '*';
    $config['max_filename'] = '255';
    $config['encrypt_name'] = FALSE;
    $config['max_size'] = '50000';
    $config['overwrite'] = TRUE;

    $this->load->library('upload', $config);

    if (isset($_FILES['file']['name'])) {
        if (0 < $_FILES['file']['error']) {
            echo 'Error during upload' . $_FILES['file']['error'];
        } else {
            if (file_exists('./uploads/' . $_FILES['file']['name'])) {
                echo 'File name already exists: ./uploads/' . $_FILES['file']['name'];
            } else {
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload('file')) {
                    echo $this->upload->display_errors();
                } else {
                    echo 'File uploaded! : ./uploads/' . $_FILES['file']['name'];
                }
            }
        }
    } else {
        echo 'Please select a file';
    }
}

Part of sendMail function:

 $archivo = $_FILES['file']['name'];
 $path = set_realpath('./uploads/');
 $adjunto = $path.$archivo;
 $this->email->attach($adjunto);

Part of the view and JS

<input type="file" id="file" name="file" />

$(document).ready(function (e) {
$('#file').on('change', function () {
  var file_data = $('#file').prop('files')[0];
  var form_data = new FormData();
  form_data.append('file', file_data);
  $.ajax({
    url: 'http://mail.mayordomus.cl/Cpersona/upload_file', 
    dataType: 'text', 
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,
    type: 'post',
    success: function (response) {
        $('#msg').html(response); 
    },
    error: function (response) {
        $('#msg').html(response);
    }
  });
});

});

Answer №1

Removing space characters from a file name can be done at the client side by using the File constructor.

let files = [new File([1], "file name.txt"), new File([2], "file name1.txt")];

let fd = new FormData();

for (let i = 0; i < files.length; i++) {
  console.log(`Original file name: ${files[i].name}`); 
  let filename = files[i].name.replace(/\s/g, "-");
  let file = new File([files[i].slice()], filename);
  fd.append("files-" + i, file);
}

for (let [, prop] of fd) {
  console.log(`FormData file name:${prop.name}`);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

Having trouble with CORS errors persisting despite configuring CORS options for Google Authentication on React/Node/Passport

Currently, I'm in the process of developing a basic application using React for the frontend and Node/Express/MongoDB for the backend. User authentication is being handled through Passport, with local authentication and Google authentication both func ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

How to extract data from URLs in Angular

Looking into how to extract a specific value from the URL within Angular for parsing purposes. For example: http://localhost:1337/doc-home/#/tips/5?paginatePage=1 The goal is to retrieve the value "5". HTML snippet: <a href="#/tips/comments/{{ tip ...

Display an image with only a portion visible, no canvas, no frame, and no need

My dilemma involves an img with a surrounding box div. http://jsfiddle.net/6d4yC/7/ 1) I am seeking to display only a portion of the image (250x150) without generating a white overlay when it is in its large size. Placing a #box1 div around the image has ...

Displaying an array value instead of a new value list in a React component

Situation - Initial number input in text field - 1 List of Items - 1 6 11 Upon removing 1 from the text field, the list becomes - New List Items - NaN NaN NaN Now, if you input 4 in the field. The updated List Items are - NaN NaN 4 9 14 Expected ...

The HTML element failed to be inserted

Currently, I am involved in a project based on .NET Core for my organization. This project entails loading work orders from our SQL database using Entity Framework and then filtering them to display as markers on a map via the Google Maps API for our insta ...

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

Cookies that are set manually in Mahara will vanish once you navigate to the next page

Currently working on some code for mahara. I am attempting to store a variable in a cookie, but it seems to disappear when I navigate to the next page. For example: foo.php: ... $myfoo = 'bar'; setcookie('mycookie', $myfoo) var_dump( ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

Accessing a Plesk website using a local IP address

I am utilizing Plesk Panel on my local Windows server, and everything is running smoothly. However, I wish to add a website that will only be accessed within my local network. Although I have added it in the conventional manner and it functions correctly ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...

Mastering image focus with javascript: A comprehensive guide

On my HTML page, I have two images and a textbox. I want the focus to shift between the images based on the first character entered in the textbox. For example, when the user types '3', the first image should be focused, and for '4', th ...

Encounter an error when reading a stream with a maximum timeout value set

I have encountered a challenge while trying to read and process large CSV files. Due to a rate limit in processing, I need to introduce a 1-minute delay between each request. Initially, I attempted to use set timeout, but discovered that there is a limitat ...

"An error has occurred: ENOENT - The specified file or directory does not exist, cannot create directory" on the live website

I am facing an issue on my website where I need to create a folder and save some files in it. While the code works perfectly fine locally, once deployed on render, I encounter the following error: Error: ENOENT: no such file or directory, mkdir '/opt/ ...

Automatically sign in and connect to the Oracle ADF application through Oracle Apex for seamless access

Currently utilizing Oracle Apex 5.1, I have a requirement in my application to access an Oracle ADF application from Oracle Apex. To achieve this, I decided to embed the ADF application within an Iframe in Apex. The issue arises when users are required to ...

Execute a JavaScript function prior to initiating an AJAX request

To streamline the process of making AJAX calls in my .NET project, I have developed a function called checkConnection that checks for internet connectivity before each call. However, currently, I am manually calling this function on every button click that ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Is it possible to convert an object with properties of equal length into a list of objects using JavaScript?

I am working with an object that has multiple keys, each containing a list of equal length: myobj = { 'key1' : [1, 2, 3], 'key2' : ['a', 'b', 'c'], 'key3' : [true, false, true], .. ...

What are some creative ways to design the selected tab?

In my Vue parent component, I have multiple child components. There are several elements that toggle between components by updating the current data. The issue is that I am unsure how to indicate which tab is currently active. I've tried various li ...