成都网站建设设计

将想法与焦点和您一起共享

android实现上传-创新互联

一丶首先服务端的代码:

成都创新互联公司从2013年创立,是专业互联网技术服务公司,拥有项目成都网站设计、网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元遂平做网站,已为上家服务,为遂平各地企业和个人服务,联系电话:18982081108

public class UploadServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
      request.setCharacterEncoding("UTF-8") ;
      response.setContentType("text/html;charset=UTF-8") ;
       PrintWriter out = response.getWriter() ;

      try {
         //1.指定上传的目录
         String storeDirectory = getServletContext().getRealPath("/WEB-INF" + File.separator + "files") ;
         //2.判断目录不存在则创建出来
         File file = new File(storeDirectory) ;
         if(!file.exists())
            file.mkdirs() ;
         //3. 创建上传的servletFileuload类
         DiskFileItemFactory dif = new DiskFileItemFactory() ;  //使用默认的临时目录

         ServletFileUpload sfu = new ServletFileUpload(dif) ;

         //多判断一步
         boolean isMultipart = sfu.isMultipartContent(request) ;
         if(!isMultipart){
            out.write("上传的enctype必须是multipart/form-data类型") ;
            return ;
         }

         //String newDirectory = makeNewDirectory(storeDirectory);

         //设置单个文件的上传大小(限制上传文件的大小不的超过2M)
//         sfu.setFileSizeMax(2*1024*1024) ;

         //设置上传总文件的大小(限制上传文件的总的大小不的超过10M))
      //   sfu.setSizeMax(10*1024*1024) ;

         //4. 解析请求
         List items = sfu.parseRequest(request) ;
         //5.判断是普通字段还是上传字段,分别处理
         for (FileItem item : items) {
            //依次判断
            if(item.isFormField()){
               //说明是普通字段
               String name = item.getFieldName() ; //拿到文本框的名字
               String value = item.getString("UTF-8") ; //拿到文本框中的内容
               System.out.println(name + "=" + value);
            }else{
               //说明是上传字段

               //限定上传的文件只能是图片
            //   if(item.getContentType().contains("p_w_picpath")){
                  //说明上传的是图片

                  //拿到上传的文件的名字
                  String filename = item.getName() ; //拿到文件名  :不包括路径
                  //如果文件名不是""则上传
                  System.out.println("上传文件名;" + filename);
                  //if("".equals(filename)){
                     filename = UUID.randomUUID() + "_" + filename ;
                     //采用文件名的hashcode计算目录名
                     String newDirectory = makeNewDirectory(storeDirectory,filename);
                     //System.out.println("filename:" + filename);
                     //System.out.println("aaaa:" + (storeDirectory + File.separator + newDirectory + File.separator + filename));
                     //构建服务器上的文件
                     File f = new File(storeDirectory + File.separator + newDirectory + File.separator + filename) ;

                     item.write(f) ;
                  //}
//               }else{
//                  out.write("只能上传图片") ;
//                  return ;
//               }
            }
         }
         out.write("上传成功") ;
      }catch (FileUploadBase.FileSizeLimitExceededException e1) {
         out.write("上传文件不得大于2M") ;
      }catch (FileUploadBase.SizeLimitExceededException e1) {
         out.write("上传总文件不得大于10M") ;
      }catch (FileUploadException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   //用文件名的hashcode计算文件目录
   private String makeNewDirectory(String storeDirectory,String filename) {
      //拿到哈希码
      int hashcode = filename.hashCode() ;
      int dir1 = hashcode&0xf;
      int dir2 = (hashcode&0xf0)>>4;
      String newDirectory = File.separator + "" + dir1 + File.separator + dir2 ;
      System.out.println(newDirectory);

      //判断目录是否存在
      File fdate = new File(storeDirectory,newDirectory) ;
      System.out.println("bb:" +fdate.getAbsolutePath());
      if(!fdate.exists())
         fdate.mkdirs() ;

      return "" + dir1 + File.separator + dir2 ;
   }

   //创建日期目录
   private String makeNewDirectory(String storeDirectory) {
      Date now = new Date() ;
      String newDirectory = new SimpleDateFormat("yyyyMMdd").format(now) ;
      File fdate = new File(storeDirectory,newDirectory) ;
      if(!fdate.exists())
         fdate.mkdirs() ;
      return newDirectory;
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
      response.setHeader("Content-Type", "text/html;charset=UTF-8");
      doGet(request, response);
   }

}

二丶android上传代码:使用API中的AsyncHttpClient连接服务器

public void click(View view){
      //拿到上传文件的路径
      String path = etpath.getText().toString().trim() ;
      //判断路径
      if(TextUtils.isEmpty(path)){
         Toast.makeText(this, "路径不能为空", 0).show() ;
         return ;
      }

      try {
         //连接服务器,上传文件
         String serverPath = "http://192.168.1.184:8080/upload/servlet/UploadServlet" ;
         //创建连接对象
         AsyncHttpClient http = new AsyncHttpClient() ;
         //设置提交的数据
         RequestParams params = new RequestParams() ;
         params.put("file", new File(path)) ;

         //发送post请求
         http.post(serverPath, params, new AsyncHttpResponseHandler(){

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                  String content) {
               super.onSuccess(statusCode, headers, content);
               Toast.makeText(MainActivity.this, "上传文件成功", 0).show() ;
            }

         }) ;
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享文章:android实现上传-创新互联
文章位置:http://chengdu.cdxwcx.cn/article/hchij.html