溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java后臺接收app上傳的圖片的示例代碼

發(fā)布時間:2020-09-20 09:52:06 來源:腳本之家 閱讀:220 作者:sujianbo 欄目:編程語言

整理文檔,搜刮出一個java后臺接受app上傳的圖片的示例代碼,稍微整理精簡一下做下分享

package com.sujinabo.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

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.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;




/**
 * Servlet implementation class FileDemo
 */
@WebServlet("/FileDemo")
public class FileDemo extends HttpServlet {
  
   /**
     * 
     */
    private static final long serialVersionUID = 564190060577130813L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
          //得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全
          String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
          //上傳時生成的臨時文件保存目錄
          String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
          File tmpFile = new File(tempPath);
          if (!tmpFile.exists()) {
            //創(chuàng)建臨時目錄
            tmpFile.mkdir();
          }
          
          //消息提示
          String message = "";
          try{
            //使用Apache文件上傳組件處理文件上傳步驟:
            //1、創(chuàng)建一個DiskFileItemFactory工廠
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //設(shè)置工廠的緩沖區(qū)的大小,當上傳的文件大小超過緩沖區(qū)的大小時,就會生成一個臨時文件存放到指定的臨時目錄當中。
            factory.setSizeThreshold(1024*100);//設(shè)置緩沖區(qū)的大小為100KB,如果不指定,那么緩沖區(qū)的大小默認是10KB
            //設(shè)置上傳時生成的臨時文件的保存目錄
            factory.setRepository(tmpFile);
            //2、創(chuàng)建一個文件上傳解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //監(jiān)聽文件上傳進度
            upload.setProgressListener(new ProgressListener(){
              public void update(long pBytesRead, long pContentLength, int arg2) {
                System.out.println("文件大小為:" + pContentLength + ",當前已處理:" + pBytesRead);
                /**
                 * 文件大小為:14608,當前已處理:4096
                  文件大小為:14608,當前已處理:7367
                  文件大小為:14608,當前已處理:11419
                  文件大小為:14608,當前已處理:14608
                 */
                float f = pBytesRead/pContentLength;
                try {
                  response.getWriter().write(f+"");
                } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
                
              }
            });
             //解決上傳文件名的中文亂碼
            upload.setHeaderEncoding("UTF-8"); 
            //3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)
            if(!ServletFileUpload.isMultipartContent(request)){
              //按照傳統(tǒng)方式獲取數(shù)據(jù)
              return;
            }
            
            //設(shè)置上傳單個文件的大小的最大值,目前是設(shè)置為1024*1024字節(jié),也就是1MB
            upload.setFileSizeMax(1024*1024);
            //設(shè)置上傳文件總量的最大值,最大值=同時上傳的多個文件的大小的最大值的和,目前設(shè)置為10MB
            upload.setSizeMax(1024*1024*10);
            //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個List<FileItem>集合,每一個FileItem對應(yīng)一個Form表單的輸入項
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem item : list){
              //如果fileitem中封裝的是普通輸入項的數(shù)據(jù)
              if(item.isFormField()){
                String name = item.getFieldName();
                //解決普通輸入項的數(shù)據(jù)的中文亂碼問題
                String value = item.getString("UTF-8");
                //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                System.out.println(name + "=" + value);
              }else{//如果fileitem中封裝的是上傳文件
                //得到上傳的文件名稱,
                String filename = item.getName();
                System.out.println(filename);
                if(filename==null || filename.trim().equals("")){
                  continue;
                }
                //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt
                //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分
                filename = filename.substring(filename.lastIndexOf("\\")+1);
                //得到上傳文件的擴展名
                String fileExtName = filename.substring(filename.lastIndexOf(".")+1);
                //如果需要限制上傳的文件類型,那么可以通過文件的擴展名來判斷上傳的文件類型是否合法
                System.out.println("上傳的文件的擴展名是:"+fileExtName);
                //獲取item中的上傳文件的輸入流
                InputStream in = item.getInputStream();
                //得到文件保存的名稱
                String saveFilename = makeFileName(filename);
                //得到文件的保存目錄
                String realSavePath = makePath(saveFilename, savePath);
                System.out.println(realSavePath);
                //創(chuàng)建一個文件輸出流
                FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
                //創(chuàng)建一個緩沖區(qū)
                byte buffer[] = new byte[1024];
                //判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標識
                int len = 0;
                //循環(huán)將輸入流讀入到緩沖區(qū)當中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù)
                while((len=in.read(buffer))>0){
                  //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath + "\\" + filename)當中
                  out.write(buffer, 0, len);
                }
                //關(guān)閉輸入流
                in.close();
                //關(guān)閉輸出流
                out.close();
                //刪除處理文件上傳時生成的臨時文件
               item.delete();
                message = "文件上傳成功!";
              }
            }
          }catch (FileUploadBase.FileSizeLimitExceededException e) {
            e.printStackTrace();
            request.setAttribute("message", "單個文件超出最大值?。?!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
          }catch (FileUploadBase.SizeLimitExceededException e) {
            e.printStackTrace();
            request.setAttribute("message", "上傳文件的總的大小超出限制的最大值?。?!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
          }catch (Exception e) {
            message= "文件上傳失??!";
            e.printStackTrace();
          }
          request.setAttribute("message",message);
          // request.getRequestDispatcher("/message.jsp").forward(request, response);
    }
    
    /**
    * @Method: makeFileName
    * @Description: 生成上傳文件的文件名,文件名以:uuid+"_"+文件的原始名稱
    * @Anthor:孤傲蒼狼
    * @param filename 文件的原始名稱
    * @return uuid+"_"+文件的原始名稱
    */ 
    private String makeFileName(String filename){ //2.jpg
      //為防止文件覆蓋的現(xiàn)象發(fā)生,要為上傳文件產(chǎn)生一個唯一的文件名
      return UUID.randomUUID().toString() + "_" + filename;
    }
    
    /**
     * 為防止一個目錄下面出現(xiàn)太多文件,要使用hash算法打散存儲
    * @Method: makePath
    * @Description: 
    * @Anthor:孤傲蒼狼
    *
    * @param filename 文件名,要根據(jù)文件名生成存儲目錄
    * @param savePath 文件存儲路徑
    * @return 新的存儲目錄
    */ 
    private String makePath(String filename,String savePath){
      //得到文件名的hashCode的值,得到的就是filename這個字符串對象在內(nèi)存中的地址
      int hashcode = filename.hashCode();
      int dir1 = hashcode&0xf; //0--15
      int dir2 = (hashcode&0xf0)>>4; //0-15
      //構(gòu)造新的保存目錄
      String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
      //File既可以代表文件也可以代表目錄
      File file = new File(dir);
      //如果目錄不存在
      if(!file.exists()){
        //創(chuàng)建目錄
        file.mkdirs();
      }
      return dir;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

      doGet(request, response);
    }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI