One place for hosting & domains

      File

      How to Fix the “Upload: Failed to Write File to Disk” Error in WordPress (3 Ways)


      Are you encountering the “Upload: Failed to write file to disk” error message when uploading files in WordPress? Whether you’re trying to add images or videos to your site, this message can be very frustrating, as it prevents you from sharing your amazing visuals with your audience.

      Fortunately, you can troubleshoot this issue by following a few simple steps. In some cases, you’ll just need to contact your web host to get it fixed.

      In this post, we’ll take a closer look at the “Upload: Failed to write file to disk” error and its main causes. We’ll then show you three simple ways to fix this problem. Let’s get started!

      What Causes the “Upload: Failed to Write File to Disk” Error in WordPress

      The “Upload: Failed to Write File to Disk” error message typically comes up when you’re trying to upload media files to your WordPress site. There are a few possible causes, the most common one being incorrect file permissions.

      Every file and folder on your WordPress site comes with a set of permissions. These are controlled by the web server and determine which site users can access and edit your files and folders. Thus, if the permissions are incorrect, you may be unable to perform certain actions on your site, such as uploading images to your media library.

      However, this error could also be caused by other issues, including a full WordPress temporary folder. It’s also possible that you’ve reached the disk space limit provided with your hosting plan.

      Next, we’ll take a closer look at these possible causes. We’ll also walk you through a solution for each scenario.

      Skip the Stress

      Avoid troubleshooting when you sign up for DreamPress. Our friendly WordPress experts are available 24/7 to help solve website problems — big or small.

      How to Fix the “Upload: Failed to Write File to Disk” Error in WordPress (3 Ways)

      Now, let’s look at three easy ways to fix this disk error in WordPress. As always, we recommend that you perform a backup of your site before proceeding. That way, if something goes wrong, you can restore your site to an earlier version.

      1. Change the File Permissions

      As we mentioned earlier, the “Upload: Failed to write file to disk” error is likely caused by incorrect file permissions. If you want to check these permissions, you can contact your hosting provider and ask them if they can do it for you. Alternatively, you can do this yourself by accessing your site’s root directory.

      First, you’ll need to connect to your site via a Secure File Transfer Protocol (SFTP) client such as FileZilla. You can also access your site’s directory through the file manager in your hosting account.

      If you have a DreamHost account, start by navigating to Websites > Files in the sidebar. Then locate your domain and click on the Manage Files button.

      Accessing your site in DreamHost

      This will take you to the file manager. To access your site’s directory, you can open the folder labeled with your domain name. Inside, locate the wp-content folder and right-click on it.

      Next, select File permissions.

      Locating the wp-content folder in your site’s root directory.

      In the pop-up window, go to the Numeric value field and enter “755” or “750” in the corresponding box. Next, you can select the Recurse into subdirectories and Apply to directories only options and click on OK.

      Changing the file permissions of your subdirectories in FileZilla.

      You have now set the correct file permissions for all subdirectories inside the wp-content folder. This includes the uploads folder, which is where your uploaded media files are stored.

      However, you’ll also need to set the correct permissions for the files within those folders. To do this, you can right-click on the wp-content folder again and select File permissions.

      In the Numeric value field, type in “644”. Then select the Recurse into subdirectories and Apply to files only options, and click on OK.

      Changing the file permissions of your files in FileZilla.

      Don’t worry if you’re still unable to upload files to your site after checking your file permissions. There are a couple of other things you can do to resolve the issue.

      2. Empty the WordPress Temporary Folder

      If changing the file permissions doesn’t solve the problem, you may need to empty your temporary folder. WordPress processes your media uploads in PHP. This means that your images are first saved in a temporary folder on your web server before being transferred to your uploads folder.

      If the temporary folder is full, WordPress won’t be able to write your files to disk until you’ve emptied it. Unfortunately, you cannot access this temporary directory via SFTP.  However, you can simply contact your hosting provider and ask them to empty the folder for you, and then check to see if the error has been resolved. If you have sudo users, you could ask them to clear your temporary folder.

      Alternatively, you can try to resolve this issue by defining a new location for WordPress to store your media (instead of the temporary folder). First, you’ll need to connect to your site via an SFTP client or the file manager. Then locate the wp-config.php file, right-click on it, and select View/Edit.

      Editing the wp-config.php file in FileZilla.

      Next, you’ll need to paste in the following code right before the line that reads “That’s all, stop editing! Happy publishing”:

      define(‘WP_TEMP_DIR’, dirname(__FILE__) . ‘/wp-content/temp/’);

      Save your changes, then navigate to the wp-content folder, open it, and create a new folder inside it called temp.

      Creating a temp folder inside the wp-content folder.

      When you’re done, you can return to your website and try to upload an image. If the file disk error was caused by the temporary folder, the issue should now be resolved.

      3. Upgrade Your Hosting Plan

      The disk error could also be a sign that you’ve outgrown your current hosting plan. For example, if you’ve been adding a lot of content to your site, including media files, new pages, and plugins, you might have used up all the disk space available in your account.

      Your web host may be able to tell you how much disk space you have left. If you’re a DreamHost client, you can check your disk usage by logging into your hosting account and navigating to Billing & Account > Disk Usage in the side menu.

      Checking your disk usage in your DreamHost account.

      If you’ve reached your disk space limit, you might need to upgrade to a more advanced hosting plan. This will give your site more room to grow. We recommend getting in touch with your hosting provider to discuss the possibility of switching to a higher plan.

      Additional WordPress Error Articles

      Do you want to learn how to resolve other technical issues on your site? We’ve put together several tutorials to help you troubleshoot the most common WordPress errors:

      If you’re looking for more information about running a WordPress site, make sure to check out our WordPress Tutorials. This is a collection of guides designed to help you navigate the WordPress dashboard like an expert.

      Take Your WordPress Website to the Next Level

      Whether you need help navigating file permission issues, choosing a web hosting provider, or finding the best plugin, we can help! Subscribe to our monthly digest so you never miss an article.

      Fix the “Upload: Failed to Write File to Disk” Error

      The “Upload: Failed to write file to disk” error message prevents you from uploading files such as images and videos to your WordPress site. Incorrect file permissions on your site normally cause this error. However, you may also be seeing this message because you’ve used all the disk space offered with your hosting plan.

      In this article, we looked at three simple ways to fix this common WordPress error:

      1. Change the file permissions of your WordPress site using an SFTP client like FileZilla.
      2. Empty the WordPress temporary folder by getting in touch with your web host.
      3. Upgrade your hosting plan to access more disk space.

      At DreamHost, we provide 24/7 expert support to help you efficiently resolve technical issues. We also offer reliable managed WordPress hosting solutions to help you grow your business while also making it easy for you to upgrade to an advanced plan as your site grows.



      Source link

      How to Fix ‘the uploaded file could not be moved to…’ in WordPress



      Part of the Series:
      Common WordPress Errors

      This tutorial series explains how to troubleshoot and fix common errors that you may encounter when deploying, maintaining, and updating your WordPress installation.

      Each tutorial in this series includes descriptions of common deployment, maintenance, or update errors, and explores ways to fix and optimize your installation to scale.

      Introduction

      When uploading new media files to your WordPress installation, you may sometimes encounter an issue that can prevent you from writing data to your site’s storage folders. This error typically happens when trying to upload images, videos, and other files to posts and pages on your WordPress site.

      In this tutorial, we’ll work to troubleshoot one common error message:

      the uploaded file could not be moved to…
      

      This error is a result of failure while attempting to upload a file to your /wp-content/uploads folder.

      Step 1 — Identifying and Replicating the Issue

      The first step in troubleshooting any issue is to attempt to gain an understanding of where the error is coming from, and how to replicate the issue. If you can isolate an issue to a certain part of your WordPress site’s code, you can better identify how to fix the issue.

      Let’s take a look at the error message:

      The uploaded file could not be moved to...
      

      From this message, we can identify that although the file was sent to the server, it was not possible to move it to the destination folder wp-content/uploads or similar. It is likely that the system user running the application doesn’t have permission to write content to the destination folder.

      WordPress files are typically hosted on a web hosting server or Droplet, and require certain permissions to work properly. If file permissions are wrong for the file or directory you’re attempting to read or write to, you may receive the error previously mentioned, or a similar error message.

      To replicate the issue, attempt to upload (or write) a new file to your intended folder. Notice the behaviors that occur up until the error, and note if the error has changed or remained the same.

      If you’ve replicated the issue, move forward to step 2 to fix the permissions issue that is preventing you from uploading to the wp-content/uploads folder or similar.

      Step 2 — Fixing Permissions in WordPress Uploads Folder

      For issues with uploading to your wp-content/uploads folder, you may again be encountering the following error messages:

      ‘The uploaded file could not be moved to wp-content/uploads/’
      
      ‘Unable to create directory wp-content/uploads/~. Is its parent directory writable by the server?’
      

      To fix this error, you’ll need terminal access to the server where your WordPress site is installed. For more information on how to log into remote servers, you can follow our guide on how to connect to Droplets with SSH, which covers this process in detail. For help with command line basics using Linux, visit A Linux Command Line Primer.

      Once you’re logged in, verify the location of your WordPress site on the server. Depending on your setup, this could be a path such as /var/www/, /usr/share/html/, or a custom location defined by the server administrator. You’ll need this information to execute the next command.

      Next, run the following command, which will set up the user www-data as owner of the WordPress uploads folder. The www-data user is typically the system user that runs the web server, both on Apache and Nginx installations. This user needs write access to the WordPress uploads folder in order to copy the uploaded file to the correct location.

      Replace the highlighted path with the path to your WordPress installation:

      • sudo chown -R www-data /var/www/mysite/wp-content/uploads

      This command evokes administrator privileges via sudo, so you may be required to provide your user’s password if this is the first time using sudo in your terminal session. This will set up correct folder permissions so that the www-data user is able to read and write data to your wp-content directory and upload folder.

      Step 3 — Testing for Errors

      After entering the aforementioned command, it’s time to test for the initial error. Try uploading a new file to your WordPress installation, and note what happens. If you’ve successfully uploaded a file, the permissions have now been set to allow you write access to the intended folder, and the issue should have been resolved.

      If you’re still receiving the error message, check with your hosting provider to understand where permissions for your WordPress installation are set, and ask for assistance in setting the correct permissions.

      You can find more information about recommended WordPress folder permissions on the official documentation.

      Conclusion

      In this tutorial, we successfully identified, corrected, and tested an issue in uploading files to the wp-content folder in a WordPress installation.

      For more on WordPress, including help with optimization, installations, and more, visit our comprehensive list of WordPress resources.



      Source link

      How to Handle File Uploads in Vue 2


      In this article, we will talk about how to handle file uploads with VueJs. We will create an images uploader that allow user to upload single or multiple images file by drag and drop or select file dialog.

      We will then upload the selected images and display them accordingly. We will also learn to filter the upload file type, for example, we only allow images, do not allow file type like PDF.

      Image uploader

      File Upload UI & API

      File upload consists of two parts: the UI (front-end) and the API (back-end). We will be using VueJs to handle the UI part. We need a backend application to accept the uploaded files. You may follow the backend tutorials or download and run either one of these server side application to handle file upload for your backend:-

      We will be using File upload with Hapi.js as our backend throughout this articles. We will also learn the tricks to enable fake upload on the front-end.

      Setup Project with Vue-Cli

      We will be using vue-cli to scaffold Vue.js projects. We will be using the webpack-simple project template.

      # install cli
      npm install vue-cli -g
      
      # then create project, with sass
      # follow the instructions to install all necessary dependencies
      vue init webpack-simple file-upload-vue
      

      Alright, all set. Let’s proceed to create our component.

      File Upload Component

      We will write our code in App.vue. Remove all the auto-generated code in the file.

      <!-- App.vue -->
      
      <!-- HTML Template -->
      <template>
        <div id="app">
          <div class="container">
            <!--UPLOAD-->
            <form enctype="multipart/form-data" novalidate v-if="isInitial || isSaving">
              <h1>Upload images</h1>
              <div class="dropbox">
                <input type="file" multiple :name="uploadFieldName" :disabled="isSaving" @change="filesChange($event.target.name, $event.target.files); fileCount = $event.target.files.length"
                  accept="image/*" class="input-file">
                  <p v-if="isInitial">
                    Drag your file(s) here to begin<br> or click to browse
                  </p>
                  <p v-if="isSaving">
                    Uploading {{ fileCount }} files...
                  </p>
              </div>
            </form>
        </div>
      </template>
      
      <!-- Javascript -->
      <script>
      </script>
      
      <!-- SASS styling -->
      <style lang="scss">
      </style>
      

      Notes:-

      1. Our App.vue component consists of 3 part: template (HTML), script (Javascript) and styles (SASS).
      2. Our template has an upload form.
      3. The form attribute enctype="multipart/form-data" is important. To enable file upload, this attribute must be set. Learn more about enctype here.
      4. We have a file input <input type="file" /> to accept file upload. The property multiple indicate it’s allow multiple file upload. Remove it for single file upload.
      5. We will handle the file input change event. Whenever the file input change (someone drop or select files), we will trigger the filesChange function and pass in the control name and selected files $event.target.files, and then upload to server.
      6. We limit the file input to accept images only with the attribute accept="image/*".
      7. The file input will be disabled during upload, so user can only drop / select files again after upload complete.
      8. We capture the fileCount of the when file changes. We use the fileCount variable in displaying number of files uploading Uploading {{ fileCount }} files....

      Style our File Upload Component

      Now, that’s the interesting part. Currently, our component look like this:

      File upload component without styling

      We need to transform it to look like this:

      File upload component with styling

      Let’s style it!

      <!-- App.vue -->
      ...
      
      <!-- SASS styling -->
      <style lang="scss">
        .dropbox {
          outline: 2px dashed grey; /* the dash box */
          outline-offset: -10px;
          background: lightcyan;
          color: dimgray;
          padding: 10px 10px;
          min-height: 200px; /* minimum height */
          position: relative;
          cursor: pointer;
        }
      
        .input-file {
          opacity: 0; /* invisible but it's there! */
          width: 100%;
          height: 200px;
          position: absolute;
          cursor: pointer;
        }
      
        .dropbox:hover {
          background: lightblue; /* when mouse over to the drop zone, change color */
        }
      
        .dropbox p {
          font-size: 1.2em;
          text-align: center;
          padding: 50px 0;
        }
      </style>
      

      With only few lines of scss, our component looks prettier now.

      Notes:-

      1. We make the file input invisible by applying opacity: 0 style. This doesn’t hide the file input, it just make it invisible.
      2. Then, we style the file input parent element, the dropbox css class. We make it look like a drop file zone surround with dash.
      3. Then, we align the text inside dropbox to center.

      File Upload Component Code

      Let’s proceed to code our component.

      <!-- App.vue -->
      ...
      
      <!-- Javascript -->
      <script>
        import { upload } from './file-upload.service';
      
        const STATUS_INITIAL = 0, STATUS_SAVING = 1, STATUS_SUCCESS = 2, STATUS_FAILED = 3;
      
        export default {
          name: 'app',
          data() {
            return {
              uploadedFiles: [],
              uploadError: null,
              currentStatus: null,
              uploadFieldName: 'photos'
            }
          },
          computed: {
            isInitial() {
              return this.currentStatus === STATUS_INITIAL;
            },
            isSaving() {
              return this.currentStatus === STATUS_SAVING;
            },
            isSuccess() {
              return this.currentStatus === STATUS_SUCCESS;
            },
            isFailed() {
              return this.currentStatus === STATUS_FAILED;
            }
          },
          methods: {
            reset() {
              // reset form to initial state
              this.currentStatus = STATUS_INITIAL;
              this.uploadedFiles = [];
              this.uploadError = null;
            },
            save(formData) {
              // upload data to the server
              this.currentStatus = STATUS_SAVING;
      
              upload(formData)
                .then(x => {
                  this.uploadedFiles = [].concat(x);
                  this.currentStatus = STATUS_SUCCESS;
                })
                .catch(err => {
                  this.uploadError = err.response;
                  this.currentStatus = STATUS_FAILED;
                });
            },
            filesChange(fieldName, fileList) {
              // handle file changes
              const formData = new FormData();
      
              if (!fileList.length) return;
      
              // append the files to FormData
              Array
                .from(Array(fileList.length).keys())
                .map(x => {
                  formData.append(fieldName, fileList[x], fileList[x].name);
                });
      
              // save it
              this.save(formData);
            }
          },
          mounted() {
            this.reset();
          },
        }
      
      </script>
      

      Notes:-

      1. Our component will have a few statuses: STATUSINITIAL, STATUSSAVING, STATUSSUCCESS, STATUSFAILED, the variable name is pretty expressive themselves.
      2. Later on, we will call the Hapi.js file upload API to upload images, the API accept a field call photos. That’s our file input field name.
      3. We handle the file changes with the filesChange function. FileList is an object returned by the files property of the HTML <input> element. It allow us to access the list of files selected with the <input type=“file”> element. Learn more [here]((https://developer.mozilla.org/en/docs/Web/API/FileList).
      4. We then create a new FormData, and append all our photos files to it. FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values. Learn more here.
      5. The save function will call our file upload service (hang on, we will create the service next!). We also set the status according to the result.
      6. mount() is the vue component life cycle hook. During that point, we will set our component status to initial state.

      File Upload Service

      Let’s proceed to create our service. We will be using axios to make HTTP calls.

      Install axios

      # install axios
      npm install axios --save
      

      Service

      // file-upload.service.js
      
      import * as axios from 'axios';
      
      const BASE_URL = 'http://localhost:3001';
      
      function upload(formData) {
          const url = `${BASE_URL}/photos/upload`;
          return axios.post(url, formData)
              // get data
              .then(x => x.data)
              // add url field
              .then(x => x.map(img => Object.assign({},
                  img, { url: `${BASE_URL}/images/${img.id}` })));
      }
      
      export { upload }
      

      Nothing much, the code is pretty expressive itself. We upload the files, wait for the result, map it accordingly.

      You may run the application now with npm run dev command. Try uploading a couple of images, and it’s working! (Remember to start your backend server)

      Display Success and Failed Result

      We can upload the files successfully now. However, there’s no indication in UI. Let’s update our HTML template.

      <!-- App.vue -->
      
      <!-- HTML Template -->
      <template>
        <div id="app">
          <div class="container">
            ...form...
      
            <!--SUCCESS-->
            <div v-if="isSuccess">
              <h2>Uploaded {{ uploadedFiles.length }} file(s) successfully.</h2>
              <p>
                <a href="https://www.digitalocean.com/community/tutorials/javascript:void(0)" @click="reset()">Upload again</a>
              </p>
              <ul class="list-unstyled">
                <li v-for="item in uploadedFiles">
                  <img :src="item.url" class="img-responsive img-thumbnail" :alt="item.originalName">
                </li>
              </ul>
            </div>
            <!--FAILED-->
            <div v-if="isFailed">
              <h2>Uploaded failed.</h2>
              <p>
                <a href="https://www.digitalocean.com/community/tutorials/javascript:void(0)" @click="reset()">Try again</a>
              </p>
              <pre>{{ uploadError }}</pre>
            </div>
          </div>
        </div>
      </template>
      

      Notes:-

      1. Display the uploaded image when upload successfully.
      2. Display the error message when upload failed.

      Fake the Upload in Front-end

      If you are lazy to start the back-end application (Hapi, Express, etc) to handle file upload. Here is a fake service to replace the file upload service.

      // file-upload.fake.service.js
      
      function upload(formData) {
          const photos = formData.getAll('photos');
          const promises = photos.map((x) => getImage(x)
              .then(img => ({
                  id: img,
                  originalName: x.name,
                  fileName: x.name,
                  url: img
              })));
          return Promise.all(promises);
      }
      
      function getImage(file) {
          return new Promise((resolve, reject) => {
              const fReader = new FileReader();
              const img = document.createElement('img');
      
              fReader.onload = () => {
                  img.src = fReader.result;
                  resolve(getBase64Image(img));
              }
      
              fReader.readAsDataURL(file);
          })
      }
      
      function getBase64Image(img) {
          const canvas = document.createElement('canvas');
          canvas.width = img.width;
          canvas.height = img.height;
      
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0);
      
          const dataURL = canvas.toDataURL('image/png');
      
          return dataURL;
      }
      
      export { upload }
      

      Came across this solution in this Stackoverflow post. Pretty useful. My online demo is using this service.

      Basically, what the code do is read the source, draw it in canvas, and save it as data url with the canvas toDataURL function. Learn more about canvas here.

      Now you can swap the real service with the fake one.

      <!-- App.vue -->
      ...
      
      <!-- Javascript -->
      <script>
        // swap as you need
        import { upload } from './file-upload.fake.service'; // fake service
        // import { upload } from './file-upload.service';   // real service
      </script>
      
      ...
      
      

      Done! Stop your backend API, refresh your browser, you should see our app is still working, calling fake service instead.

      Bonus: Delay Your Promises

      Sometimes, you may want to delay the promises to see the state changes. In our case, the file upload may complete too fast. Let’s write a helper function for that.

      // utils.js
      
      // utils to delay promise
      function wait(ms) {
          return (x) => {
              return new Promise(resolve => setTimeout(() => resolve(x), ms));
          };
      }
      
      export { wait }
      
      

      Then, you can use it in your component

      <!-- App.vue -->
      ...
      
      <!-- Javascript -->
      <script>
        import { wait } from './utils';
        ...
      
        save(formData) {
           ....
      
              upload(formData)
                .then(wait(1500)) // DEV ONLY: wait for 1.5s 
                .then(x => {
                  this.uploadedFiles = [].concat(x);
                  this.currentStatus = STATUS_SUCCESS;
                })
               ...
      
            },
      </script>
      

      Summary

      That’s it. This is how you can handle file upload without using any 3rd party libraries and plugins in Vue. It isn’t that hard right?

      Happy coding!

      The UI (Front-end)

      The API (Back-end) Tutorials and Sourcode



      Source link