一个多星期以来,我一直在努力解决这个问题!
我无法将图像从iphone发布到配置了carrierwave gem的后端rails服务器.通过网络表单发布工作得很好,同样,从iphone通过JSON发布文本也可以.
这是我的照片控制器:
class PhotosController < ApplicationController
def new
@photo = Photo.new(:user_id => params[:user_id])
end
def create
@photo = current_user.photos.build(params[:photo])
if @photo.save
respond_to do |format|
format.html { flash[:notice] = "Successfully created photo."
redirect_to @photo.user
}
format.json {
render :json => {:action => 'create', :owner => current_user}
}
end
else
render :action => 'new'
end
end
这是Objective-c代码:
UIImage *image = [UIImage imageNamed:@"moon.png"];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *urlString=[NSString stringWithFormat:@"http://127.0.0.1:3000/photos.json"];
// setting up the URL to post to
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
我从服务器得到的响应是:
“EOFError(坏内容体)”
Objective-c代码用php服务器测试,上传成功!
所以我想我的问题与我的rails / carrierwave设置有关.请帮我从我的iPhone和我的rails服务器获取血腥的图像.
非常感谢您的帮助.
最佳答案 为什么不尝试
ASIHTTPRequest进行POST?
发布多部分数据有很多方便的方法,效果很好.这样你就可以排除在你试图手动构建请求体时可能出现的错误可能引起的问题……