Rectangle 27 14

Below code is working on my live server as well as in my own Lapy.

Please Create data folder in WebContent and put in any single image or any file(jsp or html file).

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
package com.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }

            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(
                    request, response);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }

}
<servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>

Questions: (1) How do I specify an absolute path for the destination folder? (2) I'd like to pass a boolean or other message to done.jsp containing something like true (upload succeeded) or false (upload failed); how would I do that?

1 )If you are putting absolute static path to your folder then your program is not working on live server or any other server. Above program is perfect for any change the server no need to change the code.

2) you can put Boolean variable in below "item.write(uploadedFile);" line code as true and initialize with false value. So you can set the attribute in request and pass from the request dispatcher.

@VishalShah: i am not able to transfer xml,js,css file although it is working fine for txt,pdf,jpeg

java.lang.NoSuchMethodError: org/apache/commons/fileupload/servlet/ServletFileUpload.parseRequest
commons.fileupload1.2.1.jar

java - How to upload files on server folder using jsp - Stack Overflow

java image jsp servlets upload
Rectangle 27 31

When you start working on a secure image upload script, there are many things to considder. Now I'm no where near an expert on this, but I've been asked to develop this once in the past. I'm gonna walk through the entire process I've been through here so you can follow along. For this I'm gonna start with a very basic html form and php script that handles the files.

<form name="upload" action="upload.php" method="POST" enctype="multipart/form-data">
    Select image to upload: <input type="file" name="image">
    <input type="submit" name="upload" value="upload">
</form>

First problem: File types Attackers don't have to use the form on your website to upload files to your server. POST requests can be intercepted in a number of ways. Think about browser addons, proxies, Perl scripts. No matter how hard we try, we can't prevent an attacker from trying to upload something (s)he isn't supposed to. So all of our security has to be done serverside.

The first problem is file types. In the script above an attacker could upload anything (s)he wants, like a php script for example, and follow a direct link to execute it. So to prevent this, we implement Content-type verification:

<?php
if($_FILES['image']['type'] != "image/png") {
    echo "Only PNG images are allowed!";
    exit;
}

$uploaddir = 'uploads/';

$uploadfile = $uploaddir . basename($_FILES['image']['name']);

if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
    echo "Image succesfully uploaded.";
} else {
    echo "Image uploading failed.";
}
?>

Unfortunetely this isn't enough. As I mentioned before, the attacker has full control over the request. Nothing will prevent him/her from modifying the request headers and simply change the Content type to "image/png". So instead of just relying on the Content-type header, it would be better to also validate the content of the uploaded file. Here's where the php GD library comes in handy. Using getimagesize(), we'll be processing the image with the GD library. If it isn't an image, this will fail and therefor the entire upload will fail:

<?php
$verifyimg = getimagesize($_FILES['image']['tmp_name']);

if($verifyimg['mime'] != 'image/png') {
    echo "Only PNG images are allowed!";
    exit;
}

$uploaddir = 'uploads/';

$uploadfile = $uploaddir . basename($_FILES['image']['name']);

if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
    echo "Image succesfully uploaded.";
} else {
    echo "Image uploading failed.";
}
?>

We're still not there yet though. Most image file types allow text comments added to them. Again, nothing prevents the attacker from adding some php code as a comment. The GD library will evaluate this as a perfectly valid image. The PHP interpreter would completely ignore the image and run the php code in the comment. It's true that it depends on the php configuration which file extensions are processed by the php interpreter and which not, but since there are many developers out there that have no control over this configuration due to the use of a VPS, we can't assume the php interpreter won't process the image. This is why adding a file extension white list isn't safe enough either.

The solution to this would be to store the images in a location where an attacker can't access the file directly. This could be outside of the document root or in a directory protected by a .htaccess file:

order deny,allow
deny from all
allow from 127.0.0.1

Edit: After talking with some other PHP programmers, I highly suggest using a folder outside of the document root, because htaccess isn't always reliable.

We still need the user or any other visitor to be able to view the image though. So we'll use php to retrieve the image for them:

<?php
$uploaddir = 'uploads/';
$name = $_GET['name']; // Assuming the file name is in the URL for this example
readfile($uploaddir.$name);
?>

Second problem: Local file inclusion attacks Although our script is reasonably secure by now, we can't assume the server doesn't suffer from other vulnerabilities. A common security vulnerability is known as Local file inclusion. To explain this I need to add an example code:

<?php
if(isset($_COOKIE['lang'])) {
   $lang = $_COOKIE['lang'];
} elseif (isset($_GET['lang'])) {
   $lang = $_GET['lang'];
} else {
   $lang = 'english';
}

include("language/$lang.php");
?>

In this example we're talking about a multi language website. The sites language is not something considdered to be "high risk" information. We try to get the visitors prefered language through a cookie or a GET request and include the required file based on it. Now considder what will happen when the attacker enters the following url:

PHP will include the file uploaded by the attacker bypassing the fact that (s)he can't access the file directly and we're back at square one.

The solution to this problem is to make sure the user doesn't know the filename on the server. Instead, we'll change the file name and even the extension using a database to keep track of it:

CREATE TABLE `uploads` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(64) NOT NULL,
    `original_name` VARCHAR(64) NOT NULL,
    `mime_type` VARCHAR(20) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
<?php

if(!empty($_POST['upload']) && !empty($_FILES['image']) && $_FILES['image']['error'] == 0)) {

    $uploaddir = 'uploads/';

    /* Generates random filename and extension */
    function tempnam_sfx($path, $suffix){
        do {
            $file = $path."/".mt_rand().$suffix;
            $fp = @fopen($file, 'x');
        }
        while(!$fp);

        fclose($fp);
        return $file;
    }

    /* Process image with GD library */
    $verifyimg = getimagesize($_FILES['image']['tmp_name']);

    /* Make sure the MIME type is an image */
    $pattern = "#^(image/)[^\s\n<]+$#i";

    if(!preg_match($pattern, $verifyimg['mime']){
        die("Only image files are allowed!");
    }

    /* Rename both the image and the extension */
    $uploadfile = tempnam_sfx($uploaddir, ".tmp");

    /* Upload the file to a secure directory with the new name and extension */
    if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {

        /* Setup a database connection with PDO */
        $dbhost = "localhost";
        $dbuser = "";
        $dbpass = "";
        $dbname = "";

        // Set DSN
        $dsn = 'mysql:host='.$dbhost.';dbname='.$dbname;

        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );

        try {
            $db = new PDO($dsn, $dbuser, $dbpass, $options);
        }
        catch(PDOException $e){
            die("Error!: " . $e->getMessage());
        }

        /* Setup query */
        $query = 'INSERT INTO uploads (name, original_name, mime_type) VALUES (:name, :oriname, :mime)';

        /* Prepare query */
        $db->prepare($query);

        /* Bind parameters */
        $db->bindParam(':name', basename($uploadfile));
        $db->bindParam(':oriname', basename($_FILES['image']['name']));
        $db->bindParam(':mime', $_FILES['image']['type']);

        /* Execute query */
        try {
            $db->execute();
        }
        catch(PDOException $e){
            // Remove the uploaded file
            unlink($uploadfile);

            die("Error!: " . $e->getMessage());
        }
    } else {
        die("Image upload failed!");
    }
}
?>
  • We've created a secure place to save the images
  • We've processed the image with the GD library
  • We've checked the image MIME type
  • We've renamed the file name and changed the extension
  • We've saved both the new and original filename in our database
  • We've also saved the MIME type in our database

We still need to be able to display the image to visitors. We simply use the id column of our database to do this:

<?php

$uploaddir = 'uploads/';
$id = 1;

/* Setup a database connection with PDO */
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "";

// Set DSN
$dsn = 'mysql:host='.$dbhost.';dbname='.$dbname;

// Set options
$options = array(
    PDO::ATTR_PERSISTENT    => true,
    PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
);

try {
    $db = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
    die("Error!: " . $e->getMessage());
}

/* Setup query */
$query = 'SELECT name, original_name, mime_type FROM uploads WHERE id=:id';

/* Prepare query */
$db->prepare($query);

/* Bind parameters */
$db->bindParam(':id', $id);

/* Execute query */
try {
    $db->execute();
    $result = $db->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e){
    die("Error!: " . $e->getMessage());
}

/* Get the original filename */
$newfile = $result['original_name'];

/* Send headers and file to visitor */
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($newfile));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($uploaddir.$result['name']));
header("Content-Type: " . $result['mime_type']);
readfile($uploaddir.$result['name']);
?>

Thanks to this script the visitor will be able to view the image or download it with its original filename. However, (s)he can't access the file on your server direcly nor will (s)he be able to fool your server to access the file for him/her as (s)he has no way of knowing which file it is. (S)he can't brute force your upload directory either as it simply doesn't allow anyone to access the directory except the server itself.

I'd like to add that I didn't include a maximum file size into this script, but you should easily be able to do that yourself.

ImageUpload Class Due to the high demand of this script, I've writting an ImageUpload Class that should make it a lot easier for all of you to securely handle images uploaded by your website visitors. The class can handle both single and multiple files at once, and provides you with additional features like displaying, downloading and deleting images. Since the code is simply to large to post here, you can download the class from MEGA here:

Just read the README.txt and follow the instructions.

Very nice job icecub. Love the profile picture too. Thx for helping the other day.

getimagesize()
Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.

@Lachie Well you would have to adept the code to handle multiple files at once, but other than that I don't see why not :) I'm planning to turn this into a library though, so it becomes much easier to use for everyone. However, due to my busy live I don't have an ETA right now :(

@icecub That's alright. Sounds like a great idea! Good luck :)

php - Full Secure Image Upload Script - Stack Overflow

php image security file-upload upload
Rectangle 27 7

public async Task<HttpResponseMessage> PostSurveys()
    {
        // Verify that this is an HTML Form file upload request
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

            //Destination folder
            string uploadFolder = "mydestinationfolder";

            // Create a stream provider for setting up output streams that saves the output under -uploadFolder-
            // If you want full control over how the stream is saved then derive from MultipartFormDataStreamProvider and override what you need.            
            MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(uploadFolder );                
            MultipartFileStreamProvider multipartFileStreamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

            // Get the file names.
            foreach (MultipartFileData file in streamProvider.FileData)
            {
                //Do something awesome with the files..
            }
}

asp.net - how to read multi part form data in .net web api controller ...

asp.net .net asp.net-mvc asp.net-mvc-3 asp.net-web-api
Rectangle 27 60

Here is my small working sample, which uploads multiple files and uploads in a folder called as 'junk'

<html>
    <head>
    <title>Upload Example</title>
    <script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
    <script src="~/Scripts/jquery-2.1.0.js"></script>
    <script src="~/Scripts/jquery-2.1.0.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#Upload").click(function () {
            var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            for (var i = 0; i < totalFiles; i++)
            {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }
            $.ajax({
                type: "POST",
                url: '/Home/Upload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    alert('succes!!');
                },
                error: function (error) {
                    alert("errror");
                }
            });
        });
    });

</script>
</head>
<body>
    <input type="file" id="FileUpload" multiple />
    <input type="button" id="Upload" value="Upload" />
</body>
</html>
public class HomeController : Controller
{
    [HttpPost]
    public void Upload( )
    {
        for( int i = 0 ; i < Request.Files.Count ; i++ )
        {
            var file = Request.Files[i];

            var fileName = Path.GetFileName( file.FileName );

            var path = Path.Combine( Server.MapPath( "~/Junk/" ) , fileName );
            file.SaveAs( path );    
        }

    }
}

its not working in IE<10

Your code uploads the file successfully, but I always get "errror". My question is how to send the response from the controller to the ajax call?

Thanks for this. @shadi1024 to return a success result change the Upload action method signature to return an ActionResult and then return a Json result e.g. return Json(new { result = "some_info" });

jquery - File upload using MVC 4 with Ajax - Stack Overflow

jquery ajax asp.net-mvc asp.net-mvc-4
Rectangle 27 59

Here is my small working sample, which uploads multiple files and uploads in a folder called as 'junk'

<html>
    <head>
    <title>Upload Example</title>
    <script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
    <script src="~/Scripts/jquery-2.1.0.js"></script>
    <script src="~/Scripts/jquery-2.1.0.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#Upload").click(function () {
            var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            for (var i = 0; i < totalFiles; i++)
            {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }
            $.ajax({
                type: "POST",
                url: '/Home/Upload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    alert('succes!!');
                },
                error: function (error) {
                    alert("errror");
                }
            });
        });
    });

</script>
</head>
<body>
    <input type="file" id="FileUpload" multiple />
    <input type="button" id="Upload" value="Upload" />
</body>
</html>
public class HomeController : Controller
{
    [HttpPost]
    public void Upload( )
    {
        for( int i = 0 ; i < Request.Files.Count ; i++ )
        {
            var file = Request.Files[i];

            var fileName = Path.GetFileName( file.FileName );

            var path = Path.Combine( Server.MapPath( "~/Junk/" ) , fileName );
            file.SaveAs( path );    
        }

    }
}

its not working in IE<10

Your code uploads the file successfully, but I always get "errror". My question is how to send the response from the controller to the ajax call?

Thanks for this. @shadi1024 to return a success result change the Upload action method signature to return an ActionResult and then return a Json result e.g. return Json(new { result = "some_info" });

jquery - File upload using MVC 4 with Ajax - Stack Overflow

jquery ajax asp.net-mvc asp.net-mvc-4
Rectangle 27 995

When you're already on Servlet 3.0 or newer, use native API

To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.

Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.

You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.

If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.

First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    // ...
}

Then, implement its doPost() as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
    Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
    InputStream fileContent = filePart.getInputStream();
    // ... (do your job here)
}

Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

<input type="file" name="file" multiple="true" />
request.getParts("file")

Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.

private static String getSubmittedFileName(Part part) {
    for (String cd : part.getHeader("content-disposition").split(";")) {
        if (cd.trim().startsWith("filename")) {
            String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
        }
    }
    return null;
}
String fileName = getSubmittedFileName(filePart);

Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.

In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:

commons-fileupload.jar
commons-io.jar

Your initial attempt failed most likely because you forgot the commons IO.

Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldName = item.getFieldName();
                String fileName = FilenameUtils.getName(item.getName());
                InputStream fileContent = item.getInputStream();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
}

It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.

Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.

Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:

private static String getValue(Part part) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
    StringBuilder value = new StringBuilder();
    char[] buffer = new char[1024];
    for (int length = 0; (length = reader.read(buffer)) > 0;) {
        value.append(buffer, 0, length);
    }
    return value.toString();
}
String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">

Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).

Ah sorry, I was seeing request.getParts("file") and was confused x_x

With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

@BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/

If you aren't on Servlet 3.0 and use the FileUpload trick, I found you can't read the file from the request more than once. If you need this functionality, you might want to look at Spring's MultiPartFilter. This post has a good working example: stackoverflow.com/a/21448087/1048376

java - How to upload files to server using JSP/Servlet? - Stack Overfl...

java jsp java-ee servlets file-upload
Rectangle 27 989

When you're already on Servlet 3.0 or newer, use native API

To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.

Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.

You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.

If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.

First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    // ...
}

Then, implement its doPost() as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
    Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
    InputStream fileContent = filePart.getInputStream();
    // ... (do your job here)
}

Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

<input type="file" name="file" multiple="true" />
request.getParts("file")

Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.

private static String getSubmittedFileName(Part part) {
    for (String cd : part.getHeader("content-disposition").split(";")) {
        if (cd.trim().startsWith("filename")) {
            String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
        }
    }
    return null;
}
String fileName = getSubmittedFileName(filePart);

Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.

In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:

commons-fileupload.jar
commons-io.jar

Your initial attempt failed most likely because you forgot the commons IO.

Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldName = item.getFieldName();
                String fileName = FilenameUtils.getName(item.getName());
                InputStream fileContent = item.getInputStream();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
}

It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.

Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.

Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:

private static String getValue(Part part) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
    StringBuilder value = new StringBuilder();
    char[] buffer = new char[1024];
    for (int length = 0; (length = reader.read(buffer)) > 0;) {
        value.append(buffer, 0, length);
    }
    return value.toString();
}
String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">

Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).

Ah sorry, I was seeing request.getParts("file") and was confused x_x

With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

@BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/

java - How to upload files to server using JSP/Servlet? - Stack Overfl...

java jsp java-ee servlets file-upload
Rectangle 27 989

When you're already on Servlet 3.0 or newer, use native API

To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.

Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.

You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.

If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.

First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    // ...
}

Then, implement its doPost() as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
    Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
    InputStream fileContent = filePart.getInputStream();
    // ... (do your job here)
}

Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

<input type="file" name="file" multiple="true" />
request.getParts("file")

Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.

private static String getSubmittedFileName(Part part) {
    for (String cd : part.getHeader("content-disposition").split(";")) {
        if (cd.trim().startsWith("filename")) {
            String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
        }
    }
    return null;
}
String fileName = getSubmittedFileName(filePart);

Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.

In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:

commons-fileupload.jar
commons-io.jar

Your initial attempt failed most likely because you forgot the commons IO.

Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldName = item.getFieldName();
                String fileName = FilenameUtils.getName(item.getName());
                InputStream fileContent = item.getInputStream();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
}

It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.

Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.

Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:

private static String getValue(Part part) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
    StringBuilder value = new StringBuilder();
    char[] buffer = new char[1024];
    for (int length = 0; (length = reader.read(buffer)) > 0;) {
        value.append(buffer, 0, length);
    }
    return value.toString();
}
String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">

Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).

Ah sorry, I was seeing request.getParts("file") and was confused x_x

With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

@BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/

java - How to upload files to server using JSP/Servlet? - Stack Overfl...

java jsp java-ee servlets file-upload
Rectangle 27 4

Do I have to upload the html files as static files as well? how do I upload the files in the root folder as static? thanks.

yes you have to upload everything as a static file. the docs at the link i posted do explain how to do that. and this one developers.google.com/appengine/docs/python/config/ which is a mouse scroll up the link i posted above.

No matter what I do, I still end up eating frontend instance hours. I am frustrated for not being able to do it.... I used the code: -url: /(.*\.(gif|png|jpg|ico|js|css|pdf|html)) static_files: static/\1 upload: static/(.*\.(gif|png|jpg|ico|js|css|pdf|html)) AND - url: /images static_dir: static/images

please update your question or ask a new one to show the full app.yaml content and how your file structure looks like.

you need to match .html files as static files too. otherwise there will still be the MainHandler serving the files. remove the main.py part in your app.yaml and make it work without. what you want to achieve is have no python hanlders so remove that file completely.

HTML Website on Google App Engine - Stack Overflow

google-app-engine
Rectangle 27 6

If you do not use a slash, the link will point to index.html in the same folder as the page the link is on.

For example, if you have a link to index.html on the page www.example.com/page2.html then the link will take you to www.example.com/index.html. If you include a slash, it will do the same thing.

www.example.com/projects/page2.html
www.example.com/projects/index.html
www.example.com/index.html

The slash denotes the "web root."

Note that these are still considered "relative" links: they refer to a resource on the same server, regardless of the server's name. If your domain name changes or you upload it to another server, relative links will still work provided they have the same folder structure.

html - Do I need slashes before links? - Stack Overflow

html
Rectangle 27 1

I use this code to create a HTML Bootstrap page where the users upload files into a Drive Folder, named as their username and log into a spreadsheet. Maybe this helps you.

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('subirCorreo.html')
            .setSandboxMode(HtmlService.SandboxMode.NATIVE);
}

function uploadFiles(form) {

  try {

    // FOLDER ID
    var id= "FOLDERID";

    var carpeta = DriveApp.getFolderById(id);

    var blob = form.myFile;    
    var file = carpeta.createFile(blob);    

    file.setDescription("Subido por " + Session.getActiveUser().getEmail());

    // Esta linea es por si quiere tipo enlace
    // return "El archivo se subio correctamente: <br> <br>" + "<a href="+file.getUrl()+">"+file.getUrl()+"</a>" ;

    return "El archivo se subio correctamente: <br> <br>" + file.getUrl();

  } catch (error) {
    return error.toString();
  }

}

function uploadFilesMail(form) {

  try {

    var id= "FOLDERID";

    var carpeta = DriveApp.getFolderById(id);

    var correo = form.myEmail;

    var blob = form.myFile;    
    var file = carpeta.createFile(blob).setName("Archivo de: "+correo);    

    file.setDescription("Subido por " + Session.getActiveUser().getEmail());

    // Esta linea es por si quiere tipo enlace
    // return "El archivo se subio correctamente: <br> <br>" + "<a href="+file.getUrl()+">"+file.getUrl()+"</a>" ;

    return "El archivo se subio correctamente: <br> <br>" + file.getUrl();

  } catch (error) {
    return error.toString();
  }

}
<!-- Se incluye bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<style>
  form { text-align: center ; }
  input  { margin: auto;}
  div { text-align: center ;font-weight: bold; color:#3644FF;  }
</style>

<script>

  function subirArchivo() {
    google.script.run
       .withSuccessHandler(fileUploaded)
       .uploadFiles(document.getElementById("form"));
    return false;
  }

  function fileUploaded(status) {
    document.getElementById('form').style.display = 'none';
    document.getElementById('resultado').innerHTML = status;
  }

</script>

<form id="form">

 <h1> Subir archivo </h1> 

 <input type="file" name="myFile"> <br>

  <input class="btn btn-primary" type="submit" id="uploadFile" value="Subir archivo" 
         onclick="this.value='Subiendo..';subirArchivo();">

</form>

<br>
<br>
<br>
<br>

<!-- Here the results of the form submission will be displayed -->
<div id="resultado">

</div>

Google Scripts Returning Undefined - Stack Overflow

google-apps-script google-form
Rectangle 27 1

You need to to use $_FILES['UploadedPic']['tmp_name'] which is the actual file location in the tmp folder not $_FILES["UploadedPic"]["name"] which is just the name of the file.

Also you need to check that the upload went ok, because there are possible reasons the upload could fail:

$uploaddir = 'uploads/';

// Check for upload attempt
if(isset($_FILES['UploadedPic'])){
    //$newfile = $uploaddir.basename($_FILES['UploadedPic']['name']);
    $newfile = $uploaddir.'temp.png';

    // If no error
    if($_FILES['UploadedPic']['error'] == 0){
        //Attempt to move
        if (move_uploaded_file($_FILES['UploadedPic']['tmp_name'], $newfile)) {
            echo "File was successfully uploaded.";
        }else{
            echo 'Error moving file.';
        }
    } else {
        // Has error
        $errors = array(
            0=>"There is no error, the file uploaded with success",
            1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
            2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
            3=>"The uploaded file was only partially uploaded",
            4=>"No file was uploaded",
            6=>"Missing a temporary folder"
        );
        echo "Error: ".$errors[$_FILES['UploadedPic']['error']];
    }
}

Also you might want to look into checking the upload is actually an image with getimagesize()

PHP/WAMP: Failed to open stream error with uploaded file - Stack Overf...

php file-upload upload image-uploading
Rectangle 27 1

Sirko pointed you in the right direction. WordPress relies on PHP processing and MySQL database so you cannot simply upload it to the theme folder and activate. The HTML and CSS theme will need to be modified to incorporate the core WordPress theme development, at least. It isn't that difficult if you understand how WordPress works.

If you simply want to start with converting the theme to WordPress to support pages and menus alone, it isn't so complicated. If you are very new to this, it might be a stumbling block. You really should learn the core components to making a WP theme. Good luck!

html - How to import website to WordPress - Stack Overflow

html css wordpress wordpress-theming
Rectangle 27 2

I ran into a similar challenge after following the Heroku tutorial. I wanted to remove spaces from the filename and add a folder prefix based on the current project. In order to change the filename before uploading to S3, I added a submit callback where I modified the name on the client side.

fileInput.fileupload({
    ...
    submit: function (e, data) {
        // Get the original filename
        var fileName = data.originalFiles[0].name
        // Get the prefix from the form 
        var keyPrefix = form.data('key-start')
        // Combine the prefix and the original filename with start/end whitespace removed
        var fullFileName = keyPrefix + fileName.trim();
        // Replace whitespaces with underscores
        // At this step you could replace other special characters as well
        var newFileName = fullFileName.replace(/\s+/g, '_');
        // Update the form data with the new key value
        $(form.data('form-data')).attr("key", newFileName);
        // Set the form data
        data.formData = form.data('form-data');
    },
    ...
});

Since I changed the filename, I needed to ensure that S3 knows that as well. The tutorial suggested key value in the controller set_s3_direct_post method is:

key: "uploads/#{SecureRandom.uuid}/${filename}"

The key method requires that the filename match what is provided when the post URL is created (which it wouldn't because I'm not using the dynamic ${filename} value and I don't know the final filename when the direct post URL is created to specify it). I used the key_starts_with method so that I could specify the project folder prefix (with spaces removed) and S3 would just evaluate that for a match:

key_starts_with: "#{(current_project.name).strip.split(' ').join('_')}/"
set_s3_direct_post
def set_s3_direct_post
    @s3_direct_post = S3_BUCKET.presigned_post(key_starts_with: "#{(current_project.name).strip.split(' ').join('_')}/", success_action_status: '201', acl: 'public-read')
end
key_starts_with
key-start
<%= simple_form_for @asset, html: {class: 'directUpload new_asset', data: { 'form-data' => (@s3_direct_post.fields), 'key-start' => "#{current_project.name}/#{SecureRandom.hex(4)}_" , 'url' => @s3_direct_post.url, 'host' => URI.parse(@s3_direct_post.url).host  } } , :url => project_assets_path(current_project) do |f| %>
    <%= f.input :name %>
    <%= f.input :file, as: :file %>
    <%= f.button :submit, "Add File", class: "addFileButton" %>
<% end %>

In my case, I was only using this for single file uploads and only wanted to ensure spaces were removed from the filename (I was one of two users of this upload form, so special characters or other issues with the filename weren't a concern).

javascript - jQuery-File-Upload rename file before upload - Stack Over...

javascript jquery ruby-on-rails ruby amazon-s3
Rectangle 27 2

<?php
if($_POST && isset($_FILES['file']))
{
    $recipient_email    = "recipient@yourmail.com"; //recepient
    $from_email         = "info@your_domain.com"; //from email using site domain.
    $subject            = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if(strlen($sender_name)<4){
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
      die('Invalid email');
    }
    if(strlen($sender_message)<4){
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("sanwebe.com"); 

    if($file_count > 0){ //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n"; 
        $headers .= "From:".$from_email."\r\n"; 
        $headers .= "Reply-To: ".$sender_email."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
        $body .= chunk_split(base64_encode($sender_message)); 

        //attachments
        for ($x = 0; $x < $file_count; $x++){       
            if(!empty($attachments['name'][$x])){

                if($attachments['error'][$x]>0) //exit script and output error if we encounter any
                {
                    $mymsg = array( 
                    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
                    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
                    3=>"The uploaded file was only partially uploaded", 
                    4=>"No file was uploaded", 
                    6=>"Missing a temporary folder" ); 
                    die($mymsg[$attachments['error'][$x]]); 
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .="Content-Type: $file_type; name="$file_name"\r\n";
                $body .="Content-Disposition: attachment; filename="$file_name"\r\n";
                $body .="Content-Transfer-Encoding: base64\r\n";
                $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                $body .= $encoded_content; 
            }
        }

    }else{ //send plain email otherwise
       $headers = "From:".$from_email."\r\n".
        "Reply-To: ".$sender_email. "\n" .
        "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

     $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if($sentMail) //output success or failure messages
    {       
        die('Thank you for your email');
    }else{
        die('Could not send mail! Please check your PHP mail configuration.');  
    }
}
?>

Send attachments with PHP Mail()? - Stack Overflow

php
Rectangle 27 2

<?php
if($_POST && isset($_FILES['file']))
{
    $recipient_email    = "recipient@yourmail.com"; //recepient
    $from_email         = "info@your_domain.com"; //from email using site domain.
    $subject            = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if(strlen($sender_name)<4){
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
      die('Invalid email');
    }
    if(strlen($sender_message)<4){
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("sanwebe.com"); 

    if($file_count > 0){ //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n"; 
        $headers .= "From:".$from_email."\r\n"; 
        $headers .= "Reply-To: ".$sender_email."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
        $body .= chunk_split(base64_encode($sender_message)); 

        //attachments
        for ($x = 0; $x < $file_count; $x++){       
            if(!empty($attachments['name'][$x])){

                if($attachments['error'][$x]>0) //exit script and output error if we encounter any
                {
                    $mymsg = array( 
                    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
                    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
                    3=>"The uploaded file was only partially uploaded", 
                    4=>"No file was uploaded", 
                    6=>"Missing a temporary folder" ); 
                    die($mymsg[$attachments['error'][$x]]); 
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .="Content-Type: $file_type; name="$file_name"\r\n";
                $body .="Content-Disposition: attachment; filename="$file_name"\r\n";
                $body .="Content-Transfer-Encoding: base64\r\n";
                $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                $body .= $encoded_content; 
            }
        }

    }else{ //send plain email otherwise
       $headers = "From:".$from_email."\r\n".
        "Reply-To: ".$sender_email. "\n" .
        "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

     $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if($sentMail) //output success or failure messages
    {       
        die('Thank you for your email');
    }else{
        die('Could not send mail! Please check your PHP mail configuration.');  
    }
}
?>

Send attachments with PHP Mail()? - Stack Overflow

php
Rectangle 27 2

<?php
if($_POST && isset($_FILES['file']))
{
    $recipient_email    = "recipient@yourmail.com"; //recepient
    $from_email         = "info@your_domain.com"; //from email using site domain.
    $subject            = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if(strlen($sender_name)<4){
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
      die('Invalid email');
    }
    if(strlen($sender_message)<4){
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("sanwebe.com"); 

    if($file_count > 0){ //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n"; 
        $headers .= "From:".$from_email."\r\n"; 
        $headers .= "Reply-To: ".$sender_email."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
        $body .= chunk_split(base64_encode($sender_message)); 

        //attachments
        for ($x = 0; $x < $file_count; $x++){       
            if(!empty($attachments['name'][$x])){

                if($attachments['error'][$x]>0) //exit script and output error if we encounter any
                {
                    $mymsg = array( 
                    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
                    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
                    3=>"The uploaded file was only partially uploaded", 
                    4=>"No file was uploaded", 
                    6=>"Missing a temporary folder" ); 
                    die($mymsg[$attachments['error'][$x]]); 
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .="Content-Type: $file_type; name="$file_name"\r\n";
                $body .="Content-Disposition: attachment; filename="$file_name"\r\n";
                $body .="Content-Transfer-Encoding: base64\r\n";
                $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                $body .= $encoded_content; 
            }
        }

    }else{ //send plain email otherwise
       $headers = "From:".$from_email."\r\n".
        "Reply-To: ".$sender_email. "\n" .
        "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

     $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if($sentMail) //output success or failure messages
    {       
        die('Thank you for your email');
    }else{
        die('Could not send mail! Please check your PHP mail configuration.');  
    }
}
?>

Send attachments with PHP Mail()? - Stack Overflow

php
Rectangle 27 2

<?php
if($_POST && isset($_FILES['file']))
{
    $recipient_email    = "recipient@yourmail.com"; //recepient
    $from_email         = "info@your_domain.com"; //from email using site domain.
    $subject            = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if(strlen($sender_name)<4){
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
      die('Invalid email');
    }
    if(strlen($sender_message)<4){
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("sanwebe.com"); 

    if($file_count > 0){ //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n"; 
        $headers .= "From:".$from_email."\r\n"; 
        $headers .= "Reply-To: ".$sender_email."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
        $body .= chunk_split(base64_encode($sender_message)); 

        //attachments
        for ($x = 0; $x < $file_count; $x++){       
            if(!empty($attachments['name'][$x])){

                if($attachments['error'][$x]>0) //exit script and output error if we encounter any
                {
                    $mymsg = array( 
                    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
                    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
                    3=>"The uploaded file was only partially uploaded", 
                    4=>"No file was uploaded", 
                    6=>"Missing a temporary folder" ); 
                    die($mymsg[$attachments['error'][$x]]); 
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .="Content-Type: $file_type; name="$file_name"\r\n";
                $body .="Content-Disposition: attachment; filename="$file_name"\r\n";
                $body .="Content-Transfer-Encoding: base64\r\n";
                $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                $body .= $encoded_content; 
            }
        }

    }else{ //send plain email otherwise
       $headers = "From:".$from_email."\r\n".
        "Reply-To: ".$sender_email. "\n" .
        "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

     $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if($sentMail) //output success or failure messages
    {       
        die('Thank you for your email');
    }else{
        die('Could not send mail! Please check your PHP mail configuration.');  
    }
}
?>

Send attachments with PHP Mail()? - Stack Overflow

php
Rectangle 27 8

You don't need cURL to upload multiple files; you can upload a bunch of them just using a regular form.

<!-- uploader.html -->
<form enctype="multipart/form-data" method="post" action="uploader.php">
    <input name="blob[]" type="file" /><br />
    <input name="blob[]" type="file" /><br />
    <input type="submit" value="Upload these files" />
</form>
// uploader.php
if(isset($_FILES["blob"])){
    for($i = 0; $i < count($_FILES["blob"]["name"]); $i++){
        $tmp_name = $_FILES["blob"]["tmp_name"][$i];
        $blob_name = "file-name.ext"; // generate an unique name
        if(move_uploaded_file($tmp_name, "destination-folder/" . $blob_name)){
        // do something with the uploaded file
        }
    }
}
$request = curl_init('http://domain.com/uploader.php');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,
    array(
        'blob[0]' => '@' . realpath('first-file.jpg'),
        'blob[1]' => '@' . realpath('second-file.jpg')
    )
));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
curl_close($request);
//
// for the other part use the uploader.php code from above

The problem is that I want to it without the necessity to fill the form manually, thats why I am using cURL. My question here is how I get the results from the cURL. How can I get the uploaded file in the facebook.php

Well, make a file, let's say curl.php, then use the snippet from the above, make another file and name it uploader.php or facebook.php, use the other snippet I sent in my answer and that's it. Be sure to use the right path for the files and check if you have a permission to write on that uploading folder.

My ploblem is: I don't know what to write in the uploader.php/facebook.php to use the uploader file, like I did when I was using the form.

You just have it from my answer. Otherwise, you may use the same file you used before.

In my file, I had the uploaded file URL in the $uploadfile variable do I can use it later. In your answer, using the cURL, where can I find it? Thanks

Uploading multiple files in PHP using HTML Form or cURL - Stack Overfl...

php curl file-upload
Rectangle 27 4

When using the advanced template you need to decide on a common place to store your files that can be accessed by both the frontend and backend application, additionally if you want the files to be publicly accessible via the web you need to insure this location is a public folder.

I tend to use the frontend/web folder as my common upload location. When uploading from the backend I write to this location. I can then use the images in the frontend.

Example uploading form the backend.

Create a model to manage the upload data, make sure to include the file attribute.

class UploadForm extends Model
{
    /**
     * @var UploadedFile file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file', 'extensions'=>'jpg, gif, png'],
        ];
    }
}

In the controller that will be managing the upload use the alias for the frontend to set your upload path $path = Yii::getAlias('@frontend') .'/web/uploads/'

class MediaController extends Controller
{

    public function actionIndex()
    {

        $model = new UploadForm();

        //Set the path that the file will be uploaded to
        $path = Yii::getAlias('@frontend') .'/web/upload/'

        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $model->file->saveAs($path . $model->file->baseName . '.' . $model->file->extension);
            }
        }

        return $this->renderPartial('index', ['model' => $model]);

    }
}

Add a form to your view, make sure to set the 'multipart/form-data' enctype so that it can accept file uploads.

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']) ?>

    <?= $form->field($model, 'file')->fileInput(); ?>

    <?= Html::submitButton('Upload') ?>

<?php ActiveForm::end() ?>

You can then access the image in the front end via /upload/{image-name}.{extension}. example <img src="/upload/sample.png">

Note: it is a good idea to store your upload path in the common/config/params.php so that you can access from both frontend and backend.

How to upload files in root folder in yii2 advanced template? - Stack ...

yii2 yii2-advanced-app