Posting a File and Associated Data to a RESTful WebService preferably as JSON

后端 未结 11 1039
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 10:45

This is probably going to be a stupid question but I\'m having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON

11条回答
  •  佛祖请我去吃肉
    2020-11-22 11:29

    I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.

    I don't know if my approach is the best, but is so easy and simple.

    I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
    [request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
    [request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];
    
    NSURLResponse *response;
    
    NSError *error;
    
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    

    At the server side, I receive the photo using the code:

    InputStream is = request.inputStream
    
    def receivedPhotoFile = (IOUtils.toByteArray(is))
    
    def photo = new Photo()
    photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
    photo.title = request.getHeader("Photo-Title")
    photo.description = request.getHeader("Photo-Description")
    photo.imageURL = "temp"    
    
    if (photo.save()) {    
    
        File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
        saveLocation.mkdirs()
    
        File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
    
        photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
    
        tempFile.append(photo.photoFile);
    
    } else {
    
        println("Error")
    
    }
    

    I don't know if I have problems in future, but now is working fine in production environment.

提交回复
热议问题