Java、ios图片上传

来源:互联网 发布:手机直播软件制作 编辑:程序博客网 时间:2024/05/16 09:04

IOS客服端代码

@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"));// 设置缓冲区大小为 5Mfactory.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(); }}







0 2
原创粉丝点击