iOS客服端代码
iOS端代码可以直接使用AFN中的上传表单数据的方法不必从session开始写
- mark 这是AFN代码
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
- mark 从Session开始做
@interface ViewController ()
{
NSString *boundary;
NSString *fileParam;
NSString *baseUrl;
NSString *fileName;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
boundary = @"----------V2ymHFg03ehbqgZCaKO6jy";
fileParam = @"file";
baseUrl = @"http://url/from/server";
fileName = @"image.png";//此文件提前放在可读写区域
}
//请求方法
-(void)method4{
NSURL *uploadURL;
//文件路径处理(随意)
NSLog(@"请求路径为%@",uploadURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
//body
NSData *body = [self prepareDataForUpload];
//request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
[request setHTTPMethod:@"POST"];
// 以下2行是关键,NSURLSessionUploadTask不会自动添加Content-Type头
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"message: %@", message);
[session invalidateAndCancel];
}];
[uploadTask resume];
});
}
//生成bodyData
-(NSData*) prepareDataForUpload
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *uploadFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];<span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 17.600000381469727px; ">//将图片放在了documents中</span><span style="margin: 0px; padding: 0px; border: none; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 17.600000381469727px; "> </span>
NSString *lastPathfileName = [uploadFilePath lastPathComponent];
NSMutableData *body = [NSMutableData data];
NSData *dataOfFile = [[NSData alloc] initWithContentsOfFile:uploadFilePath];
if (dataOfFile) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:dataOfFile];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return body;
}
Java服务器端代码
@RequestMapping(value = "/member/headPic/save",method = RequestMethod.POST)
public void saveMemberHeadPic(HttpServletRequest request,HttpServletResponse response,
@RequestParam("token") String token){
//创建一个临时文件存放要上传的文件,第一个参数为上传文件大小,第二个参数为存放的临时目录
DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024*5,new File("D:\\temp1"));
// 设置缓冲区大小为 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 创建一个文件上传的句柄
ServletFileUpload upload = new ServletFileUpload(factory);
//设置上传文件的整个大小和上传的单个文件大小
upload.setSizeMax(1024*1024*50);
upload.setFileSizeMax(1024*1024*5);
String[] fileExts = {"doc","zip","rar","jpg","txt"};
try { //把页面表单中的每一个表单元素解析成一个
FileItem List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
//如果是一个普通的表单元素(type不是file的表单元素)
if(fileItem.isFormField()){
System.out.println(fileItem.getFieldName());
//得到对应表单元素的名字
System.out.println(fileItem.getString());
// 得到表单元素的值
}else{ //获取文件的后缀名
String fileName = fileItem.getName();//得到文件的名字
String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
if(Arrays.binarySearch(fileExts, fileExt)!=-1){
try { //将文件上传到项目的upload目录并命名,getRealPath可以得到该web项目下包含/upload的绝对路径//
fileItem.write(new File(request.getServletContext().getRealPath("/upload")+"/" + UUID.randomUUID().toString()+"."+fileExt));
fileItem.write(new File("D:/test2.png"));
logger.info("文件上传路径:"+request.getServletContext().getRealPath("/upload")+"/" + UUID.randomUUID().toString()+"."+fileExt);
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("该文件类型不能够上传");
}
}
}
} catch (FileUploadBase.SizeLimitExceededException e) {
System.out.println("整个请求的大小超过了规定的大小...");
} catch (FileUploadBase.FileSizeLimitExceededException e) {
System.out.println("请求中一个上传文件的大小超过了规定的大小...");
}catch (FileUploadException e) {
e.printStackTrace();
}
}