Java Servlet+Objective-c图上传 步骤详细
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Servlet+Objective-c图上传 步骤详细相关的知识,希望对你有一定的参考价值。
一、 Servlet
1.创建图片保存的路径
在项目的WebContent下创建一个上传图片的专属文件夹。
这个文件夹创建后,我们保存的图片就在该文件夹的真实路径下,但是在项目中是无法看到上传的图片的,访问此文件夹下的图片,使用项目的baseurl+图片文件夹+图片名称.png即可。
获取项目中图片保存路径的代码:
StringSavePath=request.getServletContext().getRealPath("/HeaderUpLoad")+"/" + Account+"UserHeader."+fileExt;
变量路径的值(这里没要图片,只是路径):/Users/liaohang/Documents/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Servlet/HeaderUpLoad/
2.访问上传图片路径
/*获取项目baseurl*/
String path = request.getContextPath();
String UserHeaderImagePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/Icons/"+Account+
"UserHeader.jpg";
变量路径的值:http://localhost:8080/Servlet/+HeaderUpLoad+图片名称.jpg
3.限制请求图片大
upload.setSizeMax(1024*1024*2);
upload.setFileSizeMax(1024*1024*2);
等会我在ios部分讲,如果处理上传图片,图片一半限制在500k内。
4.Servlet代码
更加详细的注释在代码中有。
1 package Servlet; 3 import java.io.BufferedInputStream; 4 import java.io.ByteArrayOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 import java.io.InputStream; 10 import java.io.PrintWriter; 11 import java.sql.ResultSet; 12 import java.sql.SQLException; 14 import javax.servlet.ServletException; 15 import javax.servlet.annotation.WebServlet; 16 import javax.servlet.http.HttpServlet; 17 import javax.servlet.http.HttpServletRequest; 18 import javax.servlet.http.HttpServletResponse; 20 import org.apache.tomcat.util.http.fileupload.FileItem; 21 import org.apache.tomcat.util.http.fileupload.FileItemIterator; 22 import org.apache.tomcat.util.http.fileupload.FileItemStream; 23 import org.apache.tomcat.util.http.fileupload.FileUploadBase; 24 import org.apache.tomcat.util.http.fileupload.FileUploadException; 25 import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; 26 import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; 27 import org.json.JSONArray; 28 import org.json.JSONException; 29 import org.json.JSONObject; 31 import com.amap.api.mapcore2d.v; 33 import Helper.ImageTranslateClass; 34 import Helper.mysqlHepler; 35 import Helper.ResultToJsonTool; 37 import java.util.Arrays; 38 import java.util.Iterator; 39 import java.util.List; 40 import java.util.UUID; 41 42 /** 43 * Servlet implementation class Servlet 44 */ 45 46 //@WebServlet(urlPatterns = "/servlet") 47 48 @WebServlet("/AupDownloadUserHeaderImageServlet") 49 public class AupDownloadUserHeaderImageServlet extends HttpServlet { 50 51 private static final long serialVersionUID = 1L; 52 protected final String USER_AGENT = "Mozilla/5.0"; 53 54 55 56 public AupDownloadUserHeaderImageServlet() { 57 super(); 58 // TODO Auto-generated constructor stub 59 } 60 61 /** 62 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 63 * 64 * 65 */ 66 @SuppressWarnings("resource") 67 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 68 69 70 response.setContentType( "text/html"); 71 response.setCharacterEncoding("utf-8"); 72 73 String Account; 74 int IsOrNoAddScore=0; 75 Account=request.getParameter("account"); 76 77 78 79 DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024*5,new File(request.getServletContext().getRealPath("/Icons"))); 80 // 设置缓冲区大小为 5M 81 factory.setSizeThreshold(1024 * 1024 * 5); 82 // 创建一个文件上传的句柄 83 ServletFileUpload upload = new ServletFileUpload(factory); 84 85 //设置上传文件的整个大小和上传的单个文件大小 86 upload.setSizeMax(1024*1024*50); 87 upload.setFileSizeMax(1024*1024*5); 88 String[] fileExts = {"doc","zip","rar","jpg","txt"}; 89 try { 90 @SuppressWarnings("unchecked") 91 92 /*加载所有接口请求参数,到一个文件迭代数组中。 93 */ 94 FileItemIterator list = upload.getItemIterator(request); 95 96 while(list.hasNext()){ 97 98 99 FileItemStream fileItem=list.next(); 100 /*下面判断的是参数类型,如果你的参数中,既有图片流,又有字符串类型,那么就需要判断参数的类型*/ 101 /*如果是字符串参数*/ 102 if(fileItem.isFormField()){ 103 104 String ShareTmep=fileItem.getFieldName(); 105 106 if (ShareTmep.length()==11) { 107 //保存字符串参数到一个变量中,等会修改和上传图片都需要它来拼接图片的后缀 108 Account=fileItem.getFieldName(); 109 } 110 else 111 { 112 //保存字符串参数 113 IsOrNoAddScore=Integer.parseInt(fileItem.getFieldName()); 114 115 } 116 117 118 }else{ //如果是文件类型 119 String fileName = fileItem.getName();//得到文件的名字 120 String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()); 121 if(Arrays.binarySearch(fileExts, fileExt)!=-1){ 122 try { 123 124 //获取项目存放图片的文件夹,这个文件夹就是我们需要保存上传图片的文件夹,等会我会截图出来 125 String SavePath=request.getServletContext().getRealPath("/Icons")+"/" + Account+"UserHeader."+fileExt; 126 127 128 InputStream inputImageStream= fileItem.openStream(); 129 byte[] buffer = new byte[1024]; 130 //每次读取的字符串长度,如果为-1,代表全部读取完毕 131 int len = 0; 132 //使用一个输入流从buffer里把数据读取出来 133 134 135 136 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 137 138 139 while( (len=inputImageStream.read(buffer)) != -1 ){ 140 //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 141 outStream.write(buffer, 0, len); 142 } 143 //关闭输入流 144 inputImageStream.close(); 145 //把outStream里的数据写入内存 146 147 //得到图片的二进制数据,以二进制封装得到数据,具有通用性 148 byte[] data = outStream.toByteArray(); 149 //new一个文件对象用来保存图片,默认保存当前工程根目录 150 File imageFile = new File(SavePath); 151 //创建输出流 152 FileOutputStream fileOutStream = new FileOutputStream(imageFile); 153 //写入数据 154 fileOutStream .write(data); 155 156 //获取项目的baseurl,这个获取是为了等会将这图片地址保存到用户表中对应用户的图片地址字段中 157 String path = request.getContextPath(); 158 String UserHeaderImagePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/Icons/"+Account+ 159 "UserHeader.jpg"; 160 161 162 //下面都是操作数据库 163 String[] mysqlParameter=new String[]{UserHeaderImagePath,Account}; 164 MySqlHepler.executeUpdate("update - set userHeader=? where account=?", mysqlParameter); 165 if(IsOrNoAddScore>0) 166 { 167 MySqlHepler.executeUpdate("update - set userPhoneUrl=?,userIntegral=userIntegral+5 where account=?", mysqlParameter); 168 } 169 else 170 { 171 MySqlHepler.executeUpdate("update - set userPhoneUrl=?,userIntegral=userIntegral-5 where account=?", mysqlParameter); 172 } 173 174 175 176 177 178 JSONObject returnJsonObject =new JSONObject(); 179 try { 180 returnJsonObject.put("Rows", ""); 181 returnJsonObject.put("GetType", "0"); 182 returnJsonObject.put("Success", "1"); 183 returnJsonObject.put("Msg", UserHeaderImagePath); 184 185 } catch (JSONException e) { 186 // TODO Auto-generated catch block 187 e.printStackTrace(); 188 } 189 190 response.getWriter().println(returnJsonObject.toString()); 191 } catch (Exception e) { 192 e.printStackTrace(); 193 } 194 }else{ 195 System.out.println("该文件类型不能够上传"); 196 } 197 } 198 199 200 } 201 202 203 204 } catch (FileUploadBase.SizeLimitExceededException e) { 205 System.out.println("整个请求的大小超过了规定的大小..."); 206 } catch (FileUploadBase.FileSizeLimitExceededException e) { 207 System.out.println("请求中一个上传文件的大小超过了规定的大小..."); 208 }catch (FileUploadException e) { 209 e.printStackTrace(); 210 } 211 212 }
219 }
二、 Objective-c代码
1.图片压缩
传入一个指定的尺寸,将图片压缩到指定大小。
1 /*图片压缩到指定大小*/ 2 + (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize TgeImage:(UIImage *)sourceImage 3 { 4 5 UIImage *newImage = nil; 6 CGSize imageSize = sourceImage.size; 7 CGFloat width = imageSize.width; 8 CGFloat height = imageSize.height; 9 CGFloat targetWidth = targetSize.width; 10 CGFloat targetHeight = targetSize.height; 11 CGFloat scaleFactor = 0.0; 12 CGFloat scaledWidth = targetWidth; 13 CGFloat scaledHeight = targetHeight; 14 CGPoint thumbnailPoint = CGPointMake(0.0,0.0); 15 16 if (CGSizeEqualToSize(imageSize, targetSize) == NO) 17 { 18 CGFloat widthFactor = targetWidth / width; 19 CGFloat heightFactor = targetHeight / height; 20 21 if (widthFactor > heightFactor) 22 scaleFactor = widthFactor; // scale to fit height 23 else 24 scaleFactor = heightFactor; // scale to fit width 25 scaledWidth= width * scaleFactor; 26 scaledHeight = height * scaleFactor; 27 28 // center the image 29 if (widthFactor > heightFactor) 30 { 31 thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 32 } 33 else if (widthFactor < heightFactor) 34 { 35 thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; 36 } 37 } 38 39 UIGraphicsBeginImageContext(targetSize); // this will crop 40 41 CGRect thumbnailRect = CGRectZero; 42 thumbnailRect.origin = thumbnailPoint; 43 thumbnailRect.size.width= scaledWidth; 44 thumbnailRect.size.height = scaledHeight; 45 46 [sourceImage drawInRect:thumbnailRect]; 47 48 newImage = UIGraphicsGetImageFromCurrentImageContext(); 49 if(newImage == nil) 50 NSLog(@"could not scale image"); 51 52 //pop the context to get back to the default 53 UIGraphicsEndImageContext(); 54 return newImage; 55 }
2.调用
调用获取压缩图片,并将压缩图片转换成我们要请求上传的类型nsdata
1 UIImage *TempImage=[AFDataDefine imageByScalingAndCroppingForSize:CGSizeMake(editedImage.size.width/2, editedImage.size.height/2) TgeImage:editedImage]; 2 NSData *ImageData= UIImageJPEGRepresentation(TempImage, 1.0); 3
3.http请求.
1 NSDictionary *RequestParameter=[[NSDictionary alloc]initWithObjectsAndKeys: [[WDUser currentUser] GetUserValue:@"account"],[[WDUser currentUser] GetUserValue:@"account"],IsOrNoAddScore,IsOrNoAddScore,nil]; 2 3 [SVProgressHUD showWithStatus:@"正在上传......" maskType:SVProgressHUDMaskTypeBlack]; 4 5 [[WDUser currentUser] upDownloadUserHeaderImage:RequestParameter setMethordName:@"AupDownloadUserHeaderImageServlet" ImageData:ImageData block:^(RespInfo *retobj) { 6 if (retobj.mBSuccess) { 7 8 int Score=[[[WDUser currentUser]GetUserValue:@"userIntegral"]intValue]; 9 Score=Score+[IsOrNoAddScore intValue]; 10 11 NSString *ScoreC=[NSString stringWithFormat:@"%d",Score]; 12 [[WDUser currentUser] SetUserValue:@"userIntegral" setValue: ScoreC]; 13 14 15 16 MainTableHeaderMasterView.userScoreLabel.text= [NSString stringWithFormat:@"积分:%@ 累计积分:%@",ScoreC,[[WDUser currentUser] GetUserValue:@"userTotalIntegral"]]; 17 18 NSString *NewHeaderPath=retobj.mMsg; 19 20 [[WDUser currentUser] SetUserValue:@"userPhoneUrl" setValue:NewHeaderPath]; 21 22 23 24 [UIView animateWithDuration:0.1 animations:^{ 25 [AlertBackBlackView setFrame:CGRectMake(0, DEVICE_Height+DEVICE_TabBar_Height+15,DEVICE_Width,DEVICE_Height+DEVICE_TabBar_Height+15)]; 26 27 } completion:^(BOOL finished) { 28 [UIView animateWithDuration:0.5 animations:^{ 29 30 [ContentBackView setFrame:CGRectMake(0,DEVICE_Height+DEVICE_TabBar_Height+15,DEVICE_Width,DEVICE_Height*0.41)]; 31 }]; 32 33 }]; 34 35 36 [SVProgressHUD dismiss]; 37 38 39 40 } 41 else{ 42 43 showMessage(@"修改失败,请稍候再试。"); 44 [SVProgressHUD dismiss]; 45 46 [UIView animateWithDuration:0.1 animations:^{ 47 [AlertBackBlackView setFrame:CGRectMake(0, DEVICE_Height+DEVICE_TabBar_Height+15,DEVICE_Width,DEVICE_Height+DEVICE_TabBar_Height+15)]; 48 49 } completion:^(BOOL finished) { 50 [UIView animateWithDuration:0.5 animations:^{ 51 52 [ContentBackView setFrame:CGRectMake(0,DEVICE_Height+DEVICE_TabBar_Height+15,DEVICE_Width,DEVICE_Height*0.41)]; 53 }]; 54 55 }]; 56 LoginVC *VC=[[LoginVC alloc]init]; 57 [[WDUser currentUser]logout]; 58 [self pushViewController:VC]; 59 60 61 62 } 63 64 65 }]; 66
4.封装的http调用方法
/*头像上传*/ -(void)upDownloadUserHeaderImage:(NSDictionary *)paramDic setMethordName:(NSString *)MethordName ImageData:(NSData *)imageData block:(void(^)(RespInfo* retobj))block { [[APIClient sharedClient] postUImageURL:MethordName parameters:paramDic ImageData:imageData call:^(RespInfo *info) { block(info); }]; }
-(void)postUImageURL:(NSString *)URLString parameters:(id)parameters ImageData:(NSData *)imageData call:(void (^)( RespInfo* info))callback { //首先判断是否有网络 [self checkNetWorkingIsOrNoUse:^(int StateOrType) { if (StateOrType==2) { RespInfo* retobj = [[RespInfo alloc]init]; retobj.mBSuccess=NO; NSString *AlertInfo=@"请检查网络是否畅通。"; retobj.mMsg=AlertInfo; callback(retobj); } else { NSString *Url=[NSString stringWithFormat:@"%@%@",self.baseURL,URLString]; NSString *Url1=[NSString stringWithFormat:@"%@%@",self.baseURL,URLString]; NSString *Url2=[NSString stringWithFormat:@"%@%@",self.baseURL,URLString]; [self POST:Url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithFileData:imageData name:@"file" fileName:@"touxiang.jpg" mimeType:@"image/jpeg"]; } success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { RespInfo* retobj = [[RespInfo alloc]initWithDic:responseObject]; callback( retobj ); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //UtilMethod imageWithImageSimple callback( [RespInfo infoWithError:error]); }]; } }]; }
以上是关于Java Servlet+Objective-c图上传 步骤详细的主要内容,如果未能解决你的问题,请参考以下文章
eclipse 报错:java.lang.ClassNotFoundException: org.jfree.chart.servlet.ChartDeleter
IOS / Objective-C:测试图像是不是存在[重复]
The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path