java - 将图像从 Objective-c 上传到服务器时出现损坏的文件
问题描述
你好,这是我从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”)。
小提示:
- 您应该为您的图像放置第二个内容类型标题。由于您有 JPEG,因此它应该是“Content-Disposition: ...”之后的“Content-Type: image/jpeg\r\n”。
- 这是多余的:
[body appendData:[NSData dataWithData:imageData]];
,因为[body appendData:imageData];
也可以。
检查这个答案:https ://stackoverflow.com/a/23517227/1009546
这是一个很好的例子,它应该是什么样子,如果你将你的 URL 设置为“ http://localhost:8000 ”,如果你的 iOS 模拟器发送正确的东西,你可以使用“nc -l localhost 8000”命令进行调试。