最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get absolute path of image in react `<input ="file" >` and store it in local

programmeradmin1浏览0评论

I have a simple shopping app that I made with react, react-router and bootstrap. I've got a form on a certain page where I can add a new product to the database.

There I can provide a name, description, category, and upload a product image.

The thing is when I upload an image through <input ="file">, I want to somehow get the absolute path of the image when I press open and store it inside the local state.

Till now my code is like this...

function Form() {
  const [imageUrl, setImageUrl] = useState("");

  // ... a bunch of code here

  return (
    <form style={styles.form}>

      // ... a bunch of code here

      <div className="form-group">
        <label htmlFor="image" className="form-label" style={styles.label}>
          Picture
        </label>
        <input className="form-control" type="file" id="image" required />
      </div>

      // ... a bunch of code here

    </form>
  )
}

I've tried this but that is for Jquery.

I'm new to React, so please be kind, and thanks in advance :)

I have a simple shopping app that I made with react, react-router and bootstrap. I've got a form on a certain page where I can add a new product to the database.

There I can provide a name, description, category, and upload a product image.

The thing is when I upload an image through <input ="file">, I want to somehow get the absolute path of the image when I press open and store it inside the local state.

Till now my code is like this...

function Form() {
  const [imageUrl, setImageUrl] = useState("");

  // ... a bunch of code here

  return (
    <form style={styles.form}>

      // ... a bunch of code here

      <div className="form-group">
        <label htmlFor="image" className="form-label" style={styles.label}>
          Picture
        </label>
        <input className="form-control" type="file" id="image" required />
      </div>

      // ... a bunch of code here

    </form>
  )
}

I've tried this but that is for Jquery.

I'm new to React, so please be kind, and thanks in advance :)

Share Improve this question edited May 6, 2021 at 7:35 asked May 6, 2021 at 7:29 user15813571user15813571 2
  • Did you even read the answers in the question you linked? First, there is an answer without any jQuery (for Firefox). Second it clearly states that it is not possible. – cloned Commented May 6, 2021 at 7:47
  • Like many other have already stated, you can't get the path, the best you can get is a fileHandle references that you can store and reuse if you use the new native file system access api (mostly just avalible in chrome atm) – Endless Commented May 10, 2021 at 12:56
Add a ment  | 

3 Answers 3

Reset to default 5

You have to add one onChange Function inside input tag, So while you will make onChange on same event will be trigger, on that event you will get target file path which will be like (event.target.files[0]), that you have to wrap into URL.createObjectURL. So for above code you will have to add below things, that will work:-

function Form() {
  const [imageUrl, setImageUrl] = useState("");
const fileBrowseHandler = (event) => {
        let value = URL.createObjectURL(event.target.files[0]);
        setImageUrl(value]);
    };

  return (
    <form style={styles.form}>
      <div className="form-group">
        <label htmlFor="image" className="form-label" style={styles.label}>
          Picture
        </label>
        <input className="form-control" type="file" id="image"  onChange={fileBrowseHandler} required />
      </div>

      // ... a bunch of code here

    </form>
  )
}

Short answer; you can't.

The input file element will deliberately hide the full path for security reasons:

The string is prefixed with C:\fakepath, to prevent malicious software from guessing the user's file structure. (https://developer.mozilla/en-US/docs/Web/HTML/Element/input/file)

In general, when you use the file input, it's to upload the file; you shouldn't need the path at all.

Edit for example upload to Google Drive

NOTE: this requires you to be authenticated

Assume you have your html like so:

<form id="load-image-form">
    <input type="file" id="chosen-image" accept=".jpg,.png">
    <button type="submit">Upload</button>
</form>

Then your script to upload the file would look like this:

const fileInput = document.getElementById('chosen-image')
document.getElementById('load-image-form').addEventListener('submit', e => {
    e.preventDefault();

    // check if there's any actual files chosen
    if (fileInput.files.length == 0) {
        console.log(`No files chosen`);
        return;
    }

    // assume only one file - read it, and when it's ready, upload to google drive
    const file = fileInput.files[0];
    const reader = new FileReader();
    reader.onload = () => {
        console.log(`File loaded locally - uploading`)
        fetch('https://www.googleapis./upload/drive/v3/files?uploadType=media', {
            method: 'POST',
            headers: {
                'Content-Type': file.type,
                'Content-Length': file.size
            },
            body: reader.result
        })
        .then(data => data.json())
        .then(console.log)
        .catch(console.error)
    }
    reader.readAsArrayBuffer(file);
})

Basically once the form is submitted, check if there's a file selected, if so load it using FileReader, then POST it to Google Drive

When I test this locally, I get an Authorization Login Required error, so you need to be logged in for this.

To upload it to your server (e.g. Node), use the link I posted in my ment: https://stackoverflow./a/15773267/639441

You can't get the full path due to security reasons. You can try fs-js module to work with files https://www.npmjs./package/fs-js

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论