Java Servlet+Objective-c图上传 步骤详细

时间:2023-03-08 15:47:28

一、 Servlet

1.创建图片保存的路径

在项目的WebContent下创建一个上传图片的专属文件夹。

Java Servlet+Objective-c图上传 步骤详细

这个文件夹创建后,我们保存的图片就在该文件夹的真实路径下,但是在项目中是无法看到上传的图片的,访问此文件夹下的图片,使用项目的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.访问上传图片路径

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; min-height: 15.0px }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
span.s1 { color: #7e504f }
span.s2 { color: #3933ff }
span.Apple-tab-span { white-space: pre }

/*获取项目baseurl*/

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
span.s1 { color: #7e504f }

String path = request.getContextPath();

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
span.s1 { color: #7e504f }
span.s2 { color: #3933ff }
span.Apple-tab-span { white-space: pre }

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代码

更加详细的注释在代码中有。

 package Servlet;
 import java.io.BufferedInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintWriter;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.tomcat.util.http.fileupload.FileItem;
 import org.apache.tomcat.util.http.fileupload.FileItemIterator;
 import org.apache.tomcat.util.http.fileupload.FileItemStream;
 import org.apache.tomcat.util.http.fileupload.FileUploadBase;
 import org.apache.tomcat.util.http.fileupload.FileUploadException;
 import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
 import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 import com.amap.api.mapcore2d.v;
 import Helper.ImageTranslateClass;
 import Helper.MySqlHepler;
 import Helper.ResultToJsonTool;
 import java.util.Arrays;
 import java.util.Iterator;
 import java.util.List;
 import java.util.UUID;

 /**
  * Servlet implementation class Servlet
  */

 //@WebServlet(urlPatterns = "/servlet")

 @WebServlet("/AupDownloadUserHeaderImageServlet")
 public class AupDownloadUserHeaderImageServlet extends HttpServlet {

     private static final long serialVersionUID = 1L;
     protected final String USER_AGENT = "Mozilla/5.0";

     public AupDownloadUserHeaderImageServlet() {
         super();
         // TODO Auto-generated constructor stub
     }

     /**
      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      *
      *
      */
     @SuppressWarnings("resource")
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       response.setContentType( "text/html");
         response.setCharacterEncoding("utf-8"); 

         String  Account;
         int  IsOrNoAddScore=0;
         Account=request.getParameter("account");

         DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024*5,new File(request.getServletContext().getRealPath("/Icons")));
         // 设置缓冲区大小为 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 {
             @SuppressWarnings("unchecked")

              /*加载所有接口请求参数,到一个文件迭代数组中。
               */
             FileItemIterator list =   upload.getItemIterator(request);

              while(list.hasNext()){

                  FileItemStream  fileItem=list.next();
                  /*下面判断的是参数类型,如果你的参数中,既有图片流,又有字符串类型,那么就需要判断参数的类型*/
                  /*如果是字符串参数*/
                  if(fileItem.isFormField()){   

                      String ShareTmep=fileItem.getFieldName();

                      if (ShareTmep.length()==11) {
                          //保存字符串参数到一个变量中,等会修改和上传图片都需要它来拼接图片的后缀
                          Account=fileItem.getFieldName();
                          }
                      else
                      {
                          //保存字符串参数
                          IsOrNoAddScore=Integer.parseInt(fileItem.getFieldName());

                      }

                  }else{ //如果是文件类型
                       String fileName = fileItem.getName();//得到文件的名字
                       String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                       if(Arrays.binarySearch(fileExts, fileExt)!=-1){
                          try {   

                             //获取项目存放图片的文件夹,这个文件夹就是我们需要保存上传图片的文件夹,等会我会截图出来
                              String SavePath=request.getServletContext().getRealPath("/Icons")+"/" + Account+"UserHeader."+fileExt;

                              InputStream inputImageStream=   fileItem.openStream();
                              byte[] buffer = new byte[1024];
                              //每次读取的字符串长度,如果为-1,代表全部读取完毕
                              int len = 0;
                              //使用一个输入流从buffer里把数据读取出来 

                              ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 

                              while( (len=inputImageStream.read(buffer)) != -1 ){
                              //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                              outStream.write(buffer, 0, len);
                              }
                              //关闭输入流
                              inputImageStream.close();
                              //把outStream里的数据写入内存 

                              //得到图片的二进制数据,以二进制封装得到数据,具有通用性
                              byte[] data = outStream.toByteArray();
                              //new一个文件对象用来保存图片,默认保存当前工程根目录
                              File imageFile = new File(SavePath);
                              //创建输出流
                              FileOutputStream fileOutStream = new FileOutputStream(imageFile);
                              //写入数据
                              fileOutStream .write(data); 

                              //获取项目的baseurl,这个获取是为了等会将这图片地址保存到用户表中对应用户的图片地址字段中
                               String path = request.getContextPath();
                             String UserHeaderImagePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/Icons/"+Account+
                                        "UserHeader.jpg";

                                //下面都是操作数据库
                                String[]     mysqlParameter=new String[]{UserHeaderImagePath,Account};
                                 MySqlHepler.executeUpdate("update - set userHeader=? where account=?", mysqlParameter);
                              if(IsOrNoAddScore>0)
                              {
                                MySqlHepler.executeUpdate("update - set userPhoneUrl=?,userIntegral=userIntegral+5 where account=?", mysqlParameter);
                              }
                              else
                              {
                                  MySqlHepler.executeUpdate("update - set userPhoneUrl=?,userIntegral=userIntegral-5 where account=?", mysqlParameter);
                              }

                         JSONObject returnJsonObject =new JSONObject();
                            try {
                                returnJsonObject.put("Rows", "");
                                 returnJsonObject.put("GetType", "0");
                                   returnJsonObject.put("Success", "1");
                                returnJsonObject.put("Msg", UserHeaderImagePath);

                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                               response.getWriter().println(returnJsonObject.toString());
                          } 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();
         }  

  }

二、 Objective-c代码

1.图片压缩

传入一个指定的尺寸,将图片压缩到指定大小。

 /*图片压缩到指定大小*/
 + (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize TgeImage:(UIImage *)sourceImage
 {

     UIImage *newImage = nil;
     CGSize imageSize = sourceImage.size;
     CGFloat width = imageSize.width;
     CGFloat height = imageSize.height;
     CGFloat targetWidth = targetSize.width;
     CGFloat targetHeight = targetSize.height;
     CGFloat scaleFactor = 0.0;
     CGFloat scaledWidth = targetWidth;
     CGFloat scaledHeight = targetHeight;
     CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

     if (CGSizeEqualToSize(imageSize, targetSize) == NO)
     {
         CGFloat widthFactor = targetWidth / width;
         CGFloat heightFactor = targetHeight / height;

         if (widthFactor > heightFactor)
             scaleFactor = widthFactor; // scale to fit height
         else
             scaleFactor = heightFactor; // scale to fit width
         scaledWidth= width * scaleFactor;
         scaledHeight = height * scaleFactor;

         // center the image
         if (widthFactor > heightFactor)
         {
             thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
         }
         else if (widthFactor < heightFactor)
         {
             thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
         }
     }

     UIGraphicsBeginImageContext(targetSize); // this will crop

     CGRect thumbnailRect = CGRectZero;
     thumbnailRect.origin = thumbnailPoint;
     thumbnailRect.size.width= scaledWidth;
     thumbnailRect.size.height = scaledHeight;

     [sourceImage drawInRect:thumbnailRect];

     newImage = UIGraphicsGetImageFromCurrentImageContext();
     if(newImage == nil)
         NSLog(@"could not scale image");

     //pop the context to get back to the default
     UIGraphicsEndImageContext();
     return newImage;
 }

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.http请求.

  NSDictionary *RequestParameter=[[NSDictionary alloc]initWithObjectsAndKeys: [[WDUser currentUser] GetUserValue:@"account"],[[WDUser currentUser] GetUserValue:@"account"],IsOrNoAddScore,IsOrNoAddScore,nil];

         [SVProgressHUD showWithStatus:@"正在上传......" maskType:SVProgressHUDMaskTypeBlack];

         [[WDUser currentUser]  upDownloadUserHeaderImage:RequestParameter setMethordName:@"AupDownloadUserHeaderImageServlet" ImageData:ImageData block:^(RespInfo *retobj) {
             if (retobj.mBSuccess) {

                 int Score=[[[WDUser currentUser]GetUserValue:@"userIntegral"]intValue];
                 Score=Score+[IsOrNoAddScore intValue];

                 NSString *ScoreC=[NSString stringWithFormat:@"%d",Score];
                  [[WDUser currentUser] SetUserValue:@"userIntegral" setValue:    ScoreC];

                 MainTableHeaderMasterView.userScoreLabel.text= [NSString stringWithFormat:@"积分:%@  累计积分:%@",ScoreC,[[WDUser currentUser] GetUserValue:@"userTotalIntegral"]];

                 NSString *NewHeaderPath=retobj.mMsg;

                 [[WDUser currentUser] SetUserValue:@"userPhoneUrl" setValue:NewHeaderPath];

                 [UIView animateWithDuration:0.1 animations:^{
                     [AlertBackBlackView setFrame:CGRectMake(, DEVICE_Height+DEVICE_TabBar_Height+,DEVICE_Width,DEVICE_Height+DEVICE_TabBar_Height+)];

                 } completion:^(BOOL finished) {
                     [UIView animateWithDuration:0.5 animations:^{

                         [ContentBackView setFrame:CGRectMake(,DEVICE_Height+DEVICE_TabBar_Height+,DEVICE_Width,DEVICE_Height*0.41)];
                     }];

                 }];

                 [SVProgressHUD dismiss];

             }
             else{

                 showMessage(@"修改失败,请稍候再试。");
                  [SVProgressHUD dismiss];

                 [UIView animateWithDuration:0.1 animations:^{
                     [AlertBackBlackView setFrame:CGRectMake(, DEVICE_Height+DEVICE_TabBar_Height+,DEVICE_Width,DEVICE_Height+DEVICE_TabBar_Height+)];

                 } completion:^(BOOL finished) {
                     [UIView animateWithDuration:0.5 animations:^{

                         [ContentBackView setFrame:CGRectMake(,DEVICE_Height+DEVICE_TabBar_Height+,DEVICE_Width,DEVICE_Height*0.41)];
                     }];

                 }];
                     LoginVC *VC=[[LoginVC alloc]init];
                     [[WDUser currentUser]logout];
                     [self pushViewController:VC];

             }

         }];
         

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) {
        ) {

            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]);
    }];

        }
    }];

}

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #4e9072 }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
span.s1 { color: #000000 }
span.s2 { color: #7e504f }
span.s3 { color: #3933ff }
span.Apple-tab-span { white-space: pre }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; min-height: 15.0px }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #4e9072 }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
span.s1 { color: #000000 }
span.s2 { color: #7e504f }