gpt4 book ai didi

java - 将图像从 Objective-c 上传到服务器时,我收到损坏的文件

转载 作者:行者123 更新时间:2023-11-28 23:57:56 25 4
gpt4 key购买 nike

你好,这是我在 objective-c 和 xcode 9 中所做的。服务器上的代码有效,因为我可以从 Android 上传好的文件图像。我尝试进行一些更改,但我在服务器上遇到了同样的错误。

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"my-url"]];

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *connection = @"Keep-Alive";
[request addValue:connection forHTTPHeaderField:@"Connection"];

NSString *boundary = @"*****";
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 stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",newName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];
NSLog(@"Request body %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);

NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
NSLog(@"%@", [request allHTTPHeaderFields]);

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if(data.length > 0) {
//success
NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response %@",responseString);
NSError *error;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
if(error == nil){
if([[responseDictionary objectForKey:@"ok"]boolValue]) {
NSString *fileURL = [[responseDictionary objectForKey:@"file"] objectForKey:@"url_download"];
NSLog(@"File URL %@", fileURL);
} else {
NSLog(@"Could Not upload file ");
}
}
}
}] resume];

下面的代码包含来自服务器的解码图像的方法。当我从 Android 代码发送相同的多部分表单时,该代码工作正常。

@POST
@Path("/uploadFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {

String output = "-1";
if (contentDispositionHeader.getFileName().split("~@~").length > 2) {

String codMun = contentDispositionHeader.getFileName().split("~@~")[0];
String fileName = contentDispositionHeader.getFileName().split("~@~")[1] + "~@~"
+ contentDispositionHeader.getFileName().split("~@~")[2];
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + "/resources/" + fileName;

if (fileInputStream != null) {
if (saveFile(fileInputStream, filePath) < 0) {
Response.status(200).entity("{\"error\":\"-2\"}").build();
}
output = "{\"error\":\"0\"}";

} else {
return Response.status(200).entity("{\"error\":\"-1\"}").build();
}
}

return Response.status(200).entity(output).build();
}


private int saveFile(InputStream uploadedInputStream, String serverLocation) {

int flagExit = -1;
try {

OutputStream outpuStream = new FileOutputStream(new File(serverLocation));

if (outpuStream != null) {

int read = 0;
byte[] bytes = new byte[1024];

while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
flagExit = 1;
}
} catch (IOException e) {
logger.error("Error Output : ", e);
flagExit = -3;
e.printStackTrace();
}
return flagExit;

}

最佳答案

查看代码,我对其进行了一些简化(删除了不相关的行并重新排列),我能够发现一些错误:

  • 在正文的开头有一个空行,您不需要它(它是由库自动插入的)。
  • 边界 stringWithFormat 之前或之后有“--”,你不需要它。如果您愿意,可以在边界内添加“--”,但不是必须这样做。重要的是所有边界都匹配。
  • 正文中的 imageData 之前缺少一个空行。您的数据从“Content-Disposition”之后的下一行开始,但中间需要有一个空行(只需“\r\n”)。

小笔记:

  • 您应该为图像添加第二个内容类型 header 。由于您有 JPEG,因此在“Content-Disposition:...”之后应该是“Content-Type:image/jpeg\r\n”。
  • 这是多余的:[bodyappendData:[NSData dataWithData:imageData]];,因为 [bodyappendData:imageData]; 也可以工作。

检查这个答案:https://stackoverflow.com/a/23517227/1009546

这是一个很好的示例,说明了它应该是什么样子,如果您将 URL 设置为“http://localhost:8000 ”,并且 iOS 模拟器发送了正确的内容,则可以使用“nc -l localhost 8000”命令进行调试。

关于java - 将图像从 Objective-c 上传到服务器时,我收到损坏的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50585035/

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