2012-09-23 2 views
2

지금 내 레일 앱에서 Carrierwave를 사용하여 Amazon S3에 파일을 업로드하고 있습니다. 파일 선택기와 양식을 사용하여 파일을 선택하고 제출하면 잘됩니다.Carrierwave 프로그래밍 방식 업로드

그러나 이제 iPhone 앱에서 게시물을 작성하려고하고 있으며 파일의 내용을 받고 있습니다. 이 데이터를 사용하여 파일을 만든 다음 Carrierwave를 사용하여 업로드하여 정확한 경로를 다시 가져오고 싶습니다. 경로는 아마존 S3 URL을이다

path 
file_name 
id 
user_id 

: 모델을 제기 할 수 있습니다

이 구성되어 있습니다. 나는 파일을 구축하기 위해이 같은 일을하고 싶습니다 :

data = params[:data] 
~file creation magic using data~ 
~carrierwave upload magic using file~ 
@user_id = params[:id] 
@file_name = params[:name] 
@path = path_provided_by_carrierwave_magic 
File.build(@user_id, @file_name, @path) 

정말 올바른 방향으로 날 가리 키도록 누군가를 사랑겠습니까. 감사!

답변

0

좋아, 나는 해결책이있다. 다른 사람들이 내 경험을 통해 배울 수 있도록 내가 한 일을 가장 잘 설명 할 것입니다. 여기 간다 :

당신이 사진을 소요 아이폰 애플 리케이션이 가정 : 나는 모바일 이미지를 처리하기위한 구체적 방법을 설정 레일 측면에서

//handle the image that has just been selected 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    //get the image 
    UIImage* image = [info valueForKey:@"UIImagePickerControllerOriginalImage"]; 

    //scale and rotate so you're not sending a sideways image -> method provided by http://blog.logichigh.com/2008/06/05/uiimage-fix/ 
    image = [self scaleAndRotateImage:image]; 

    //obtain the jpeg data (.1 is quicker to send, i found it better for testing) 
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, .1)]; 

    //get the data into a string 
    NSString* imageString = [NSString stringWithFormat:@"%@", imageData]; 
    //remove whitespace from the string 
    imageString = [imageString stringByReplacingOccurrencesOfString:@" " withString:@""]; 
    //remove <and> from string 
    imageString = [imageString substringWithRange:NSMakeRange(1, [imageString length]-2)]; 

    self.view.hidden = YES; 
    //dismissed the camera 
    [picker dismissModalViewControllerAnimated:YES]; 

    //posts the image 
    [self performSelectorInBackground:@selector(postImage:) withObject:imageString]; 
} 

- (void)postImage:(NSString*)imageData 
{ 
    //image string formatted in json 
    NSString* imageString = [NSString stringWithFormat:@"{\"image\": \"%@\", \"authenticity_token\": \"\", \"utf8\": \"✓\"}", imageData]; 

    //encoded json string 
    NSData* data = [imageString dataUsingEncoding:NSUTF8StringEncoding]; 

    //post the image 
    [API postImage:data]; 
}[/code] 

Then for the post: 

[code]+(NSArray*)postImage:(NSData*) data 
{ 
    //url that you're going to send the image to 
    NSString* url = @"www.yoururl.com/images"; 

    //pretty self explanatory request building 
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; 

    [request setTimeoutInterval:10000]; 

    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

    [request setHTTPMethod: @"POST"]; 

    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

    [request setHTTPBody:data]; 

    NSError *requestError; 
    NSURLResponse *urlResponse = nil; 

    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError]; 

    return [API generateArrayWithData:result]; 
} 

을, 이것은 당신이 아마존에 이미지를 게시 할 수 있도록해야한다 Carrierwave를 통한 S3 계정 :

def post 
     respond_to do |format| 
    format.json { 
#create a new image so that you can call it's class method (a bit hacky, i know) 
    @image = Image.new 
#get the json image data 
    pixels = params[:image] 
#convert it from hex to binary 
pixels = @image.hex_to_string(pixels) 
#create it as a file 
    data = StringIO.new(pixels) 
#set file types 
    data.class.class_eval { attr_accessor :original_filename, :content_type } 
    data.original_filename = "test1.jpeg" 
    data.content_type = "image/jpeg" 
#set the image id, had some weird behavior when i didn't 
    @image.id = Image.count + 1 
#upload the data to Amazon S3 
    @image.upload(data) 
#save the image 
    if @image.save! 
    render :nothing => true 
    end 
    } 
    end 
    end 

이 게시물은 저에게 적합하며 매우 확장 가능해야합니다. 클래스 메소드의 경우 :

#stores the file 
    def upload(file) 
    self.path.store!(file) 
    end 

#converts the data from hex to a string -> found code here http://4thmouse.com/index.php/2008/02/18/converting-hex-to-binary-in-4-languages/ 
    def hex_to_string(hex) 
    temp = hex.gsub("\s", ""); 
    ret = [] 
    (0...temp.size()/2).each{|index| ret[index] = [temp[index*2, 2]].pack("H2")} 
    file = String.new 
    ret.each { |x| file << x} 
    file 
    end 

이 코드는 완벽하지 않으며, 장황한 경우조차도 아닙니다. 그러나, 그것은 나를 위해 일한다. 나는 누군가가 그것을 향상시킬 수 있다고 생각한다면 제안에 개방적이다. 희망이 도움이!

먼저 사진 모델

class Photo 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    mount_uploader :image, PhotoImageUploader 

    field :title, :type => String 
    field :description, :type => String 
end 

API에서 두 번째 :: V1 :: PhotosController

: 여기
2

내가 carrierwave를 통해 IOS 응용 프로그램에서 S3하는 업로드를 수행하기 위해 쓴 것입니다
def create 
    @photo = current_user.photos.build(params) 
    if @photo.save 
     render :json => @photo.to_json, :status=>201 
    else 
     render :json => {:errors => @photo.errors}.to_json, :status=>403 
    end 
end 

내 iPhone 응용 프로그램에서 호출을 사용하여 AFNetworking

-(void) sendNewPhoto 
{ 
    NSURL *url = [NSURL URLWithString:@"http://myserverurl.com"]; 

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:_photoTitle.text, @"title", _photoDescription.text, @"description",nil]; 

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 

    NSString *endUrl = [NSString stringWithFormat:@"/api/v1/photos?auth_token=%@", [[User sharedInstance] token]]; 

    NSData *imageData = UIImageJPEGRepresentation(_photo.image, 1.0); 
    NSURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:endUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
     [formData appendPartWithFileData:imageData name:@"image" fileName:@"image.jpg" mimeType:@"image/jpg"]; 
    }]; 

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     NSLog(@"%@", JSON); 
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
     NSLog(@"Error creating photo!"); 
     NSLog(@"%@", error); 
    }]; 

    [operation start]; 
} 

JSON 응답에서 image.url 속성을 s3의 url로 설정하여 Photo의 새 인스턴스를 가져올 수 있습니다.