Solving the File Upload Issue in Magento Contact Form
Hello everybody! I hope this post finds you well.
Today, we’re going to solve an issue that comes up quite often - how to upload files via the contact form in your Magento store.
The Current Situation: What Went Wrong
Our friend here has done a good job so far. They’ve added the file input field to the form.phtml and set the correct enctype. They’ve also updated the IndexController.php to handle the file upload.
However, they’re facing two issues:
- The file is not being uploaded to the specified directory (
medias/contacts/). - In the email sent after submission, an attachment called “noname” appears instead of the actual filename.
Let’s Debug and Fix These Issues
Issue 1: File Not Being Uploaded
The problem lies in these lines:
$uploader = new Varien_File_Uploader('attachment');
...
$uploader->save($path . DS, $fileName );
There are a few things going wrong here.
Firstly, the $path variable is concatenated with DS, but DS is not defined anywhere in the scope. It should be replaced with /.
Secondly, the $fileName is being set twice - once inside the try block and again outside it. This can lead to the second instance overwriting the first.
Lastly, the file upload code is being executed twice due to the double try...catch blocks. This will result in a “noname” attachment if a file error occurs during the first execution.
Issue 2: “Noname” Attachment
This issue is directly related to the previous one. If an exception is thrown inside either of the try blocks (due to a validation or file upload error), the code will jump out and execute the second try...catch block where a new $uploader instance is created.
Since the setAllowRenameFiles(false) method was called, the filename won’t be changed by Magento. Therefore, if an exception occurs during the first upload attempt, you’ll end up with a “noname” attachment in your email because of the second (and successful) upload attempt.
The Solution: Fixing the Code
Let’s fix these issues:
//... previous code ...
public function postAction()
{
//... existing code before the try block ...
try {
$post = $this->getRequest()->getPost();
if ($post) {
//... validation and file upload logic ...
// Only keep the first try-catch block for file uploading
/**************************************************************/
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'pdf')); // Add allowed extensions
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . '/contacts'; // Use / instead of DS
if (!is_dir($path)) {
mkdir($path, 0777, true);
}
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, "."), 1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+/', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader->save($path . '/', $fileName );
//... continue with the email sending logic ...
} catch (Exception $e) {
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to upload your file. Please, try again later'));
$this->_redirect('*/*/');
return;
}
}
//... rest of the code ...
}
} catch (Exception $e) {
// Handle other exceptions
}
//... existing code after the try block ...
}
//... rest of the controller code ...
The Fix Explained
-
I’ve replaced
DSwith/. This ensures that the file is saved in the correct directory. -
I’ve removed the second
try...catchblock for handling the file upload. This prevents the “noname” attachment issue by ensuring the filename set inside the first try block is used. -
I’ve added comments explaining the purpose of certain lines and blocks to make the code easier to understand.
-
I’ve included error messages for both general submission failures and specific file upload errors to provide better feedback to the user.
Conclusion
In this post, we’ve identified the root causes of the file upload issue in Magento’s contact form and fixed them by modifying the IndexController.php file.
Remember, always include the enctype attribute when dealing with file uploads. Ensure that you handle exceptions properly during the file upload process to provide meaningful feedback to your users.
I hope this helps! Let me know if you have any questions or need further assistance in the comments below.
Happy coding!
[Backlinks]
- For more Magento development tips and tutorials, check out our Magento Development Blog at Laravel Company.
- If you’re looking to hire a professional for your Magento project, visit our Magento Expert Services page.