简体   繁体   中英

Convert a file into a downloadable file in url - javascript

Is it possible to upload a file who is locally stored in our computer, in a server, and have a final url to download it ?

Like this exemple ( this is an excel file ) :

http://mapa.aji-france.com/mapa/file/marche/18143/DPGF%20VIERGE%20URUGUAY%20LABORATOIRES%20H174-H176-BUANDERIE.xls

I need to do this because i'm using an API (who do a excel preview with a .xls file on a web page), and we need to have the url of the file..

You need some server-side mechanism to handle the uploaded file (eg a PHP script or a servlet or whatnot). You cannot directly access the server file system with Javascript, as Javascript runs locally in the user's browser. So just create a simple server side script that stores the uploaded file and returns the server side file location.

You need to do more research around this until you can attempt it. Heres a quick overview using PHP, I know you specified Javascript but PHP is very good at this.

You would have to create two files, a html file where you can upload the file from graphically, and a PHP file to take that file and put it on the server.

The HTML:

<form hidden action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="fileToUpload" class="ui button">
    <input type="submit" value="upload" name="submit" class="ui primary button">
</form>

The php upload.php :

<?php
   $target_file = "where/to/upload/remotely" . basename($_FILES["fileToUpload"]["name"]);
   move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file) or die ("failed");
?>

You should store both these files in your public html directory, usually /var/www/html on unix. The PHP file needs permissions that allow it to be executed. Theres a bit of configuration to this which would be hard to explain online, this is just showing you a very simple abstraction of how it would work.

On submission of the html form, so on submit button clicked, upload.php is executed (as its the action of the form), this gets the filename and moves it onto the specified directory on the server.

Then assuming the upload was successful the remote file name would be the same as the files original name. So say I uploaded hello.txt to thisserver.net , the remote path would be thisserver.net/hello.txt

This code assumes you have a webserver installed, such as apache2 . It also assumes you have php configured to work with said webserver.

Read this for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM