Asked  7 Months ago    Answers:  5   Viewed   66 times

I'm trying to upload an image with parameters in Swift. When I try this code, I can get the parameters but not the image

    var foto =  UIImage(data: UIImageJPEGRepresentation(fotiño, 0.2))

    var request = NSMutableURLRequest(URL:NSURL(string: "URL"))
    request.HTTPMethod = "POST"

    var bodyData = "id_user="PARAMETERS&ETC""

    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(foto))
    println("miraqui (request.debugDescription)")
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var HTTPError: NSError? = nil
    var JSONError: NSError? = nil

    var dataVal: NSData? =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: &HTTPError)

    if ((dataVal != nil) && (HTTPError == nil)) {
        var jsonResult = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: &JSONError)

        if (JSONError != nil) {
            println("Bad JSON")
        } else {
    } else if (HTTPError != nil) {
        println("Request failed")
    } else {
        println("No Data returned")

edit 2:

I think that I have some problems with the path of the saved UIImage, because php tells me that the file already exist, which I think is because I send it in blank

func createRequest (#userid: String, disco: String, id_disco: String, pub: String, foto: UIImage) -> NSURLRequest {
    let param = [
        "id_user"  : userid,
        "name_discoteca"    : disco,
        "id_discoteca" : id_disco,
        "ispublic" : pub] // build your dictionary however appropriate

    let boundary = generateBoundaryString()

    let url = NSURL(string: "http....")
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.timeoutInterval = 60
    request.HTTPShouldHandleCookies = false
    request.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
    var imagesaver = ImageSaver()

    var image = foto  // However you create/get a UIImage
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let destinationPath = documentsPath.stringByAppendingPathComponent("VipKing.jpg")
    UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)

    self.saveImage(foto, withFileName: "asdasd22.jpg")

    var path = self.documentsPathForFileName("asdasd22.jpg")

    self.ViewImage.image = self.loadImageWithFileName("asdasd22.jpg")

  //  let path1 = NSBundle.mainBundle().pathForResource("asdasd22", ofType: "jpg", inDirectory: path) as String! 

    **//path1 always crash**


    request.HTTPBody = createBodyWithParameters(param, filePathKey: "asdasd22.jpg", paths: [path], boundary: boundary)


    return request



In your comment below, you inform us that you are using the $_FILES syntax to retrieve the files. That means that you want to create a multipart/form-data request. The process is basically:

  1. Specify a boundary for your multipart/form-data request.

  2. Specify a Content-Type of the request that specifies that it multipart/form-data and what the boundary is.

  3. Create body of request, separating the individual components (each of the posted values as well as between each upload).

For more detail, see RFC 7578. Anyway, in Swift 3 and later, this might look like:

/// Create request
/// - parameter userid:   The userid to be passed to web service
/// - parameter password: The password to be passed to web service
/// - parameter email:    The email address to be passed to web service
/// - returns:            The `URLRequest` that was created

func createRequest(userid: String, password: String, email: String) throws -> URLRequest {
    let parameters = [
        "user_id"  : userid,
        "email"    : email,
        "password" : password]  // build your dictionary however appropriate

    let boundary = generateBoundaryString()

    let url = URL(string: "")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")

    let fileURL = Bundle.main.url(forResource: "image1", withExtension: "png")!
    request.httpBody = try createBody(with: parameters, filePathKey: "file", urls: [fileURL], boundary: boundary)

    return request

/// Create body of the `multipart/form-data` request
/// - parameter parameters:   The optional dictionary containing keys and values to be passed to web service.
/// - parameter filePathKey:  The optional field name to be used when uploading files. If you supply paths, you must supply filePathKey, too.
/// - parameter urls:         The optional array of file URLs of the files to be uploaded.
/// - parameter boundary:     The `multipart/form-data` boundary.
/// - returns:                The `Data` of the body of the request.

private func createBody(with parameters: [String: String]?, filePathKey: String, urls: [URL], boundary: String) throws -> Data {
    var body = Data()

    parameters?.forEach { (key, value) in
        body.append("Content-Disposition: form-data; name="(key)"rnrn")

    for url in urls {
        let filename = url.lastPathComponent
        let data = try Data(contentsOf: url)
        let mimetype = mimeType(for: filename)

        body.append("Content-Disposition: form-data; name="(filePathKey)"; filename="(filename)"rn")
        body.append("Content-Type: (mimetype)rnrn")

    return body

/// Create boundary string for multipart/form-data request
/// - returns:            The boundary string that consists of "Boundary-" followed by a UUID string.

private func generateBoundaryString() -> String {
    return "Boundary-(UUID().uuidString)"

/// Determine mime type on the basis of extension of a file.
/// This requires `import MobileCoreServices`.
/// - parameter path:         The path of the file for which we are going to determine the mime type.
/// - returns:                Returns the mime type if successful. Returns `application/octet-stream` if unable to determine mime type.

private func mimeType(for path: String) -> String {
    let pathExtension = URL(fileURLWithPath: path).pathExtension as NSString

        let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
        let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue()
    else {
        return "application/octet-stream"

    return mimetype as String


extension Data {

    /// Append string to Data
    /// Rather than littering my code with calls to `data(using: .utf8)` to convert `String` values to `Data`, this wraps it in a nice convenient little extension to Data. This defaults to converting using UTF-8.
    /// - parameter string:       The string to be added to the `Data`.

    mutating func append(_ string: String, using encoding: String.Encoding = .utf8) {
        if let data = encoding) {

Having all of this, you now need to submit this request. I would advise this is done asynchronously. For example, using URLSession, you would do something like:

let request: URLRequest

do {
    request = try createRequest(userid: userid, password: password, email: email)
} catch {

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        // handle error here
        print(error ?? "Unknown error")

    // parse `data` here, then parse it

    // note, if you want to update the UI, make sure to dispatch that to the main queue, e.g.:
    // DispatchQueue.main.async {
    //     // update your UI and model objects here
    // }

For Swift 2 renditions, see previous revision of this answer.

Tuesday, June 1, 2021
answered 7 Months ago

This would work for you

Sample HTML

<form action="" enctype="multipart/form-data" method="post">

        Please specify a file, or a set of files:<br> <input type="file"
            name="image[]" size="40">

        Please specify a file, or a set of files:<br> <input type="file"
            name="image[]" size="40">

        Please specify a file, or a set of files:<br> <input type="file"
            name="image[]" size="40">

        Please specify a file, or a set of files:<br> <input type="file"
            name="image[]" size="40">

        Please specify a file, or a set of files:<br> <input type="file"
            name="image[]" size="40">

        <input type="submit" value="Send">

PHP Code

$allowedExtention = array (
$errors = array ();
$output = array ();

if (! empty ( $_FILES ['image'] ['tmp_name'] )) {

    foreach ( $_FILES ['image'] ['name'] as $key => $array_value ) {

        $fileName = $_FILES ['image'] ['name'] [$key];
        $fileSize = $_FILES ['image'] ['size'] [$key];
        $fileTemp = $_FILES ['image'] ['tmp_name'] [$key];

        $fileExtention = pathinfo ( $fileName, PATHINFO_EXTENSION );
        $fileExtention = strtolower ( $fileExtention );

        if (! in_array ( $fileExtention, $allowedExtention )) {
            $errors [$fileName] [] = "File format $fileExtention not accepted for $fileName";

        if ($fileSize > 2097152) {
            $errors [$fileName] [] = 'reached maxsize of 2MB per file in picture $variable_that_count';
continue ;

        if (count ( $errors ) == 0) {
            $path = "temp";
            $prifix = basename ( $fileName, "." . $fileExtention );

            var_dump ( $prifix );

            $uploadfile = $path . "/" . $fileName;
            $x = 0;
            while ( file_exists ( $uploadfile ) ) {
                $x ++;
                $uploadfile = "{$path}/{$prifix}-{$x}.{$fileExtention}";

            if (move_uploaded_file ( $fileTemp, $uploadfile )) {
                $fileName = basename ( $uploadfile );
                $output [$fileName] = "OK";
            } else {
                $output [$fileName] = "ERORR";
                $errors [$fileName] [] = "Can Move uploaded file to destination";

var_dump ( $errors );
var_dump ( $output );

Sample Output

string '79534296' (length=8)
string '89773706' (length=8)
  'download (1)' => 
      0 => string 'File format  not accepted for download (1)' (length=42)
  'brief.docx' => 
      0 => string 'File format docx not accepted for brief.docx' (length=44)
  '' => 
      0 => string 'File format  not accepted for ' (length=30)
  '79534296-2.jpg' => string 'OK' (length=2)
  '89773706-2.jpg' => string 'OK' (length=2)

Edit 1

if all the files must be valid there are 2 ways to achieve that

A. Start By validating all files first ;

foreach ( $_FILES ['image'] ['name'] as $key => $array_value ) {
    if(! in_array (pathinfo ($_FILES ['image'] ['name'] [$key], PATHINFO_EXTENSION ), $allowedExtention ))
        die("Die! Die! Die") ;

foreach ( $_FILES ['image'] ['name'] as $key => $array_value ) {
  // Upload Script here 

B. Remove all files if an error is detected

foreach ( $_FILES ['image'] ['name'] as $key => $array_value ) {
  // Upload Script here 

// Remove All Files
if(count($errors) > 0)
    foreach ($output as $key => $value)
        @unlink($path . "/" . $key);

    die("Die! die! die!") ;

I hope this helps

Saturday, May 29, 2021
answered 7 Months ago

Looks like your PHP is correct.

On your device use HTTP POST request with MultipartEntity data type. Read more here


Example from my link:

You will have to download additional libraries to get MultipartEntity running!

1) Download from and add apache-mime4j-0.6.1.jar to your project.

2) Download from and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.

3) Use the example code below.

    private DefaultHttpClient mHttpClient;

    public ServerCommunication() {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        mHttpClient = new DefaultHttpClient(params);

    public void uploadUserPhoto(File image1, File image2, File image3) {

        try {

            HttpPost httppost = new HttpPost("some url");

            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
            multipartEntity.addPart("Title", new StringBody("Title"));
            multipartEntity.addPart("Nick", new StringBody("Nick"));
            multipartEntity.addPart("Email", new StringBody("Email"));
            multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
            multipartEntity.addPart("file1", new FileBody(image1));
            multipartEntity.addPart("file2", new FileBody(image2));
            multipartEntity.addPart("file3", new FileBody(image3));

            mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

        } catch (Exception e) {
            Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);

    private class PhotoUploadResponseHandler implements ResponseHandler {

        public Object handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {

            HttpEntity r_entity = response.getEntity();
            String responseString = EntityUtils.toString(r_entity);
            Log.d("UPLOAD", responseString);

            return null;


Wednesday, July 28, 2021
answered 5 Months ago

You are confused between media and static. Hopefully this will clarify the matter:

Static Files

Static files are files that are shipped as part of your application.

STATIC_ROOT is where the collectstatic command will dump all static files, so you can move them to the production web server.

You don't need to mess with STATIC_ROOT during development.

In your case, you have an application Vote, and inside it you have a static folder. That's all you need to serve static files during development. All you have to do is {% static 'folder/filename.ext' %} where folder is the folder inside static that contains your file.

So if your directory structure is:

 - migrations
 - static
   - vote
     - images
       - foo.jpg

You need <img src="{% static 'vote/images/foo.jpg' %}">

Media Files

Media files are what django calls files that are uploaded by your application's users

For uploading files, you need to set a location where all uploaded files are stored. This location is the parent directory and its universal across your entire project. The setting for this is MEDIA_ROOT. This should be a full system file path.

Suppose you set MEDIA_ROOT = '/home/foo/bar/proj/media', and in your models you have:

image = models.ImageField(upload_to='logos/')

Files for the model will be uploaded to /home/foo/bar/proj/media/logos/.

To display these files, you need to tell django the name of a link that points to the MEDIA_ROOT directory, this setting is MEDIA_URL.

For development, you need to do three things:

  1. Set MEDIA_URL to /media/

  2. Configure to serve media files:

    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  3. Add '' to context_processors in TEMPLATES. This will activate {{ MEDIA_URL }} in your templates.

Wednesday, October 27, 2021
answered 2 Months ago

The actual problem is not with the initial file size but with the dimensions of the image itself (heightwidthcolorDepth), since you don't have access to this information before the file has been uploaded for security reasons, you should probably use an uploader written in Flash, Java or Silverlight since they DO have access to this information beforehand.

After the upload you can check if the image will exceed your memory limit by calculating the dimensions of the (uncompressed) image by using getimagesize and using the returned width, height and bit depth.

Best of luck.

Thursday, November 18, 2021
Peter Bridger
answered 3 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :