当我向 ASP.net 服务器发送请求(来自 objective-c )时,我收到未设置对象引用到 object.postmethod POST 文件名文件的实例作为响应。
objective-c 代码
NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"arrow-next"]);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:@"http://aamc.kleward.com/OfflineCourse/iphone_Upload.aspx"]
cachePolicy:NSURLCacheStorageNotAllowed
timeoutInterval:120.0f];
[request addValue:@"text/plain; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request addValue:[data base64Encoding] forHTTPHeaderField:@"file"];
[request addValue:@"myimage.png" forHTTPHeaderField:@"filename"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSLog(@"response--%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
else{
NSLog(@"error--%@",connectionError);
}
}];
ASP.net代码
private string UploadFile(byte[] file, string fileName)
{
// the byte array argument contains the content of the file
// the string argument contains the name and extension
// of the file passed in the byte array
string sJSON = "{\"Root\":[";
try
{
// instance a memory stream and pass the
// byte array to its constructor
MemoryStream ms = new MemoryStream(file);
// instance a filestream pointing to the
// storage folder, use the original file name
// to name the resulting file
FileStream fs = new FileStream(//System.Web.Hosting.HostingEnvironment.MapPath
System.Configuration.ConfigurationManager.AppSettings["PDPointFile"].ToString() + fileName, FileMode.Create);
// write the memory stream containing the original
// file as a byte array to the filestream
ms.WriteTo(fs);
// clean up
ms.Close();
fs.Close();
fs.Dispose();
// return OK if we made it this far
sJSON += "{\"Value\":\"True\",";
sJSON += "\"File Path\":\"" + System.Configuration.ConfigurationManager.AppSettings["PDPointFilePath"].ToString() + fileName + "\"}]}";
Response.Write(sJSON);
return sJSON;
}
catch (Exception ex)
{
sJSON += "{\"Value\":\"False\",";
sJSON += "\"File Path\":\"\"}]}";
Response.Write(ex.Message);
Response.Write(sJSON);
return sJSON;
// return the error message if the operation fails
// return ex.Message.ToString();
}
}
// getting value.
protected void Page_Load(object sender, EventArgs e)
{
try
{
postmethod = Request.HttpMethod;
if (Request.HttpMethod == "POST")
{
str_filename = Request.Form["filename"].ToString();
tokenID = Server.UrlDecode(Request.Form["file"].ToString().Replace(" ", "+"));
tokenID = tokenID.Replace(" ", "+");
str_file = Convert.FromBase64String(tokenID);
UploadFile(str_file, str_filename);
}
}
catch (Exception ex)
{
Response.Write(ex.Message + "postmethod " + postmethod + " filename " + str_filename + " file " + tokenID);
}
}
编辑:
工作 Android 代码
HttpClient httpClient = new DefaultHttpClient();
mv = new MyVars();
myUrl = mv.upload_file + pick_image_name + "&file=" + imageEncoded ;
myUrl = myUrl.replaceAll("\n", "");
myUrl = myUrl.replaceAll(" ", "%20");
System.out.println("Complete Add statement url is : " + myUrl);
HttpPost httppost = new HttpPost("http://aamc.kleward.com/OfflineCourse/iphone_Upload.aspx"); // Setting URL link over here
try {
// Add your data ... Adding data as a separate way ...
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("filename", pick_image_name));
nameValuePairs.add(new BasicNameValuePair("file", imageEncoded));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("================== URL HTTP ===============" + httppost.toString());
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httppost);
// System.out.println("httpResponse"); // use this httpresponse for JSON Object.....
InputStream inputStream = response.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
jsonString = stringBuilder.toString();
System.out.println("Complete response is : " + jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
我无法理解响应,任何人都可以告诉我这些响应的含义 Object reference not set to an instance of an object.postmethod POST filename file
为什么它与 Android 代码一起工作?
最佳答案
在您的 ASP.NET 页面中,您正在从发布的表单 中读取文件和文件名。
在您的 Android 代码中,您将文件和文件名添加到 form 并且您的 ASP.NET 页面能够读取它,所以没有问题。
但是,在您的 objective-c 代码中,您将文件和文件名添加到请求的 header 中,因此 ASP.NET 文件试图读取它们从表单中抛出异常,因为它试图读取 null 的表单变量。
只需尝试在 Objective C 代码中将文件和文件名添加到表单而不是标题,一切都会成功。
NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"arrow-next"]);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:@"http://aamc.kleward.com/OfflineCourse/iphone_Upload.aspx"]
cachePolicy:NSURLCacheStorageNotAllowed
timeoutInterval:120.0f];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
NSString *postString = [NSString stringWithFormat:@"filename=%@&file=%@",@"myimage.png",[data base64Encoding]] ;
data = [postString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[data length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSLog(@"response--%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else{
NSLog(@"error--%@",connectionError);
}
}];
关于ios - 上传图像时对象引用未设置为 object.postmethod POST 文件名文件的实例,但**与 Android 代码一起正常工作**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22283595/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta