0

How to Upload pdf file located in document directory to server.

Appreciate for help

Vinod Jadhav
  • 1,055
  • 1
  • 15
  • 37

1 Answers1

5

SWIFT 2.0 : Use below code to convert pdf file to NSData. And use the POST service to upload the data to server.

    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    var filePath = documentDirectory.stringByAppendingString("/")
    filePath     = filePath.stringByAppendingString("final.pdf")
    let pdfData  = NSData(contentsOfFile: filePath)

Here, "filePath" is the path of the pdf file in document directory with name "final.pdf".

iOS
  • 5,450
  • 5
  • 23
  • 25
  • Is there a way we can upload without converting file to NSData? – hacker_1989 Jan 17 '17 at 19:56
  • You cannot upload the file directly to the server. It is required to be converted into the required format for communication. You can do the upload by converting file to Base64Encoded String. But, for this also the conversion will be like this : File -> NSData -> Base64String. It also depends on which format is being supported by the server. Also look for these references : http://stackoverflow.com/questions/34012883/upload-image-without-converting-nsdata http://stackoverflow.com/questions/20417347/is-it-possible-to-upload-a-file-to-server-without-converting-it-into-nsdata – iOS Jan 18 '17 at 07:51
  • Suppose I have a 500 mb large image. I have stored it locally and I want to upload that image. I do 1. data = NSData(contentsOfFile: filePath) 2. var image = UIImage(data: data) 3. Check image orientation using extension like image.checkImageOrientation(). Then I convert the image to NSData using UIImageJPEGRepresentation it surges the memory usage to 4GBs. I do not want that the surge as it crashes the app. – hacker_1989 Jan 18 '17 at 19:24
  • As size of image is bigger, you will be required to scale the image proportionally to reduce the size without losing the quality of the image before doing any format conversion. In steps : Scale the Image -> Get new scaled image -> Convert to NSData or Base64 String -> Upload – iOS Jan 19 '17 at 06:03