您的位置:首页 > 编程语言 > Java开发

IOS上传文件到JAVA服务器

2015-10-10 15:18 435 查看
在开发过程中我们可能会需要把IOS上传到java服务器。

IOS端

首先我们来观察下在form表单中上传文件到服务中http header中的内容。



红色框里面是我们需要的内容。

再观察wireshark中所发送的data的内容



然后我们根据上文中的内容为需要发送的文件的data数据中添加必要的内容。

模仿下面红色框的格式。

定义data:注意需要完全按照wireshark中的格式来,一定要带上”\r\n”

格式:

–boundary

Content-Disposition:form-data;name=”表单控件名称”;filename=”上传文件名称”

Content-Type:文件MIME Types

文件二进制数据;

—boundary–

//构造Content-Type

NSMutableData *uData = [NSMutableData data];
//Content-Type head
NSString *strTop = [NSString stringWithFormat:@"------%@\r\nContent-Disposition: form-data; name=\"file1\"; filename=\"%@\"\r\nContent-Type: %@\r\n\r\n",BODUNDARY_STRING,fileName,[self mimeType:fileName]];
//Content_Type foot
NSString *strBottom = [NSString stringWithFormat:@"\r\n------%@--\r\n",BODUNDARY_STRING];

//文件数据
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
NSData *uploadData = [NSData dataWithContentsOfFile:filePath];
if (!uploadData) {
NSLog(@"no uploadData!!");
}
[uData appendData:[strTop dataUsingEncoding:NSUTF8StringEncoding]];
[uData appendData:uploadData];
[uData appendData:[strBottom dataUsingEncoding:NSUTF8StringEncoding]];


其实data的格式为前后都是boundary,可以为任何字符串。中间为我们需要上传的文件内容

在IOS中我们可以通过NSURLSessionUploadTask来上传文件。

首先定义一个NSURLRequest

NSURL *url = [NSURL URLWithString:[@"http://localhost:8080/IOS/upload/file.do"stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];//为了可以传递中文指定字符集
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f];


然后为request添加必要的内容

[request setHTTPMethod:@"POST"];
//数据体
[request setHTTPBody:uploadData];
//设置请求头
[request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)uploadData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=----%@",BODUNDARY_STRING] forHTTPHeaderField:@"Content-Type"];//多部分表单数据,支持浏览器访问,不进行任何编码,通常用于文件传输(此时传递的是二进制数据) 。


然后上传文件

NSURLSessionUploadTask *_task = [[self session] uploadTaskWithRequest:request fromData:uploadData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"系统提示" message:dataStr preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:sureAction];
dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:alert animated:YES completion:nil];
});
}];


JAVA端

java端采用了springMVC框架。

1.导入commons-fi’leupload-1.3.1.jar

2.在springMVC配置文件中定义如下

<!-- 上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>


3.在对应的Controller中的具体方法

@Controller
@RequestMapping(value = "/upload")
public class UploadController {

@RequestMapping(value = "/file.do",method = RequestMethod.POST)
@ResponseBody
public String upload(MultipartHttpServletRequest muiltRequest,HttpServletRequest servletRequest) throws Exception{
String resultString = "";
String filename = "";//源文件名
String fileName = muiltRequest.getFileNames().next(); //得到文件名(注意。是content-type 中的name="file1",而不是真正的文件名)
MultipartFile file = muiltRequest.getFile(fileName);   //得到该文件
if (file.getOriginalFilename().length() > 0) {

filename = new String(file.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8");//中文转码,得到源文件名

//得到工程文件目录
String path = this.getClass().getResource("/").getPath();
path = path.replaceAll("(.)/\\..*", "$1") + servletRequest.getContextPath(); //到工程目录
String filePath = path + "/WebContent/upload";

File uploadFile = new File(filePath,     //建立本地文件
filename);

InputStream inputStream = file.getInputStream();
FileUtils.copyInputStreamToFile(inputStream,  //把获取的文件存储到指定位置
uploadFile);
filename = new String(filename.getBytes(),"ISO-8859-1");//转码返回
resultString = filename + " upload Success";
}

return resultString;


这样就完成了IOS上传文件到java服务器。这里需要注意的是。在定义header的时候。\r\n一定要带上。可根据wireshark中的格式写。否则在服务器端会出错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: