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

NodeJS unexpectedly exhibiting peculiar array functions

Within my NodeJS code, I have the following implementation: /* server.js */ 'use strict'; const http = require('http'), url = require('url'); METHODS = ['GET','POST','PUT','DELETE&a ...

Using AngularJS to add an element to an array based on a specified condition

dashboardCtrl Data app.controller('dashboardCtrl', ['$scope','$rootScope', function ($scope, $rootScope) { //Color $scope.Color = [{ colorname: "Red", number: "(3)" }, { colorname: "Brown ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Transferring information via Ajax causes backslashes to be generated in SQL queries

I haven't been able to find any similar issues. My form is populated with values from a SQL database. When I edit the input fields and save changes, an ajax call is triggered. In this particular case, I'm only updating one field, 'email&ap ...

Transmit information via AJAX to the @RequestBody annotation in a Spring application

When working with Spring Java, I used response entity and request body to insert data but encountered an error - 404 not found. This is my controller: @RequestMapping(value = "insertuserlogin/", method = RequestMethod.POST) public ResponseEntity<?> ...

Leverage the power of an Express server to manage a Node.js application

I have a node.js application that communicates with a REST API hosted on a separate server. To control this application, I want to create a web interface using express.js which includes HTML, CSS, and Javascript. How can I enable the browser to interact w ...

Retrieve the JSON data within the foreach iteration

Check out my JSON link here: click here Retrieve the data for stage name, start time, and name. $jsonData = file_get_contents("http://varzesht.com/my/live.php"); foreach($jsonData as $data) { echo $data->stage_name; foreach($jsonData->match ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

Retrieve JSON data from MySQL using PHP, only returning a result when a single row is found

Currently, I am working on writing PHP code on an online server running php 7.2.4. My main objective is to extract data from the database located on this server. It seems that when only a single row is returned by the SQL query, the JSON output works fine ...

capture the alteration of text within an input field

Currently, I am utilizing the Joomla calendar feature to select a date. The HTML code for this functionality is displayed below. When you click on the image, a calendar will pop up allowing you to choose a date. Once selected, the popup closes and the date ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Modifying a string in PHP before inserting it into a database

I am looking to save a method for performing a specific task in a database field. However, I want to store this method as a string including HTML tags. For instance, the following list should be included: <ul> <li>List item</li> <li&g ...

What is the best way to make changes to elements in an express array?

I have been developing an express application that enables users to manage a list of web projects through various HTTP methods such as get, post, put, and delete. So far, I have successfully implemented the logic for handling get, delete, and post reques ...

Using jQuery Ajax to send an associative array with keys containing spaces to PHP in a unique way

My challenge lies in passing my keys correctly to my PHP server. Here is a snippet of the code I am working with: ajax: { url: "<?= base_url("items/getTableData") ?>", type: "POST", dataType: "json", ...

Having trouble displaying results in Vue.js after making an API request?

I am facing challenges in displaying the results using vue.js. The data from my API (ASP.NET CORE) is being retrieved successfully, as shown in my vue dev tools on Google Chrome. However, I am encountering difficulties in rendering the results on the brows ...

Transmit a JSON object while simultaneously receiving the corresponding response

As part of a school project, I need to work with JSON. The server will process the file and send back a response in JSON format. This entire exchange needs to be done using JavaScript. I recently learned about the XMLHttpRequest object, but I'm still ...

Ways to showcase specific values from PHP options

Within my database, I have established four distinct values for various pricing plans: - Star (plan_id = 1) - Moon (plan_id = 2) - Sun (plan_id = 3) - Galaxy (plan_id = 4) Specifically on the signup page, my goal is to showcase only plan_id 2 & 3. Is this ...

Issues with PHP and Oracle Authentication Logon page on Apache server running on Windows 2008 operating system

[UPDATE: Issue Resolved: Grateful for everyone's assistance. View updated code here: http://pastebin.com/1fJmXeG2] I am seeking help with a challenge I'm facing. We currently have a login page on our website that is hosted on an older Linux serve ...

npm will only update when modifications are made to index.js

Recently diving into the world of React, I've encountered an issue with updating my website when making changes to files within my project. While modifications to the index.js file reflect on the site, any adjustments made to imported apps do not get ...