gpt4 book ai didi

ios - 上传图像时对象引用未设置为 object.postmethod POST 文件名文件的实例,但**与 Android 代码一起正常工作**

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:35:52 25 4
gpt4 key购买 nike

当我向 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com