分享

nginx upload在java中的应用

 WindySky 2016-07-04
1.Nginx上传介绍

    文件在POST上传到nginx服务器时,nginx会自己将这个文件先保存下来,然后再往后端发送。
    在这个过程中,文件会被保存成一个临时文件,待文件传送完成后,nginx向后端(如resin)通知临时文件的文件信息(如上传文件原有的文件名、存在本地磁盘哪个目录下、临时文件名、文件的md5、文件的类型、文件的大小等)。
    后端服务拿到这个文件名可以直接读取缓存的文件,进行迁移转码等后续逻辑。


2.安装
下载nginx upload模块
http://www./nginx/upload.en.html
Java代码  收藏代码
  1. tar zxvf nginx_upload_module-2.2.0.tar.gz  


在nginx添加该模块
Java代码  收藏代码
  1. ./configure --prefix=/usr/local/nginx --with-pcre=/root/pcre-8.11 --with-http_stub_status_module --with-http_realip_module --add-module=/root/nginx_upload_module-2.2.0 --add-module=/root/masterzen-nginx-upload-progress-module-3d8e105/  


3.配置nginx.conf
Java代码  收藏代码
  1. # Upload form should be submitted to this location  
  2. location /upload {  
  3.         # Pass altered request body to this location  
  4.         upload_pass   @test;  
  5.   
  6.         upload_pass_args  on;  
  7.         upload_max_file_size 1m;  
  8.   
  9.         # Store files to this directory  
  10.         # The directory is hashed, subdirectories 0 1 2 3 4 5 6 7 8 9 should exist  
  11.         upload_store /tmp 1;  
  12.   
  13.         # Allow uploaded files to be read only by user  
  14.         upload_store_access user:r;  
  15.         # Set specified fields in request body  
  16.         upload_set_form_field "${upload_field_name}.name" $upload_file_name;  
  17.         upload_set_form_field "${upload_field_name}.content_type" $upload_content_type;  
  18.         upload_set_form_field "${upload_field_name}.path" $upload_tmp_path;  
  19.   
  20.         # Inform backend about hash and size of a file  
  21.         #upload_aggregate_form_field "${upload_field_name}.md5" $upload_file_md5;  
  22.         upload_aggregate_form_field "${upload_field_name}.crc32" $upload_file_crc32;  
  23.         upload_aggregate_form_field "${upload_field_name}.size" $upload_file_size;  
  24.         upload_pass_form_field "^submit$|^test$";  
  25.   
  26.         upload_cleanup 400 404 499 500-505;  
  27.   
  28. }  
  29.   
  30. # Pass altered request body to a backend  
  31. location @test {  
  32.         proxy_pass   http://resin;  
  33.         proxy_set_header Host $host;  
  34.         proxy_set_header X-Real-IP $remote_addr;  
  35.         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
  36. }  


指定上传文件的大小
Java代码  收藏代码
  1. keepalive_timeout  200;  
  2. client_max_body_size 100m;  


二、.resin端程序的接收
1.上传的页面index.html
Java代码  收藏代码
  1. <html>  
  2. <head>  
  3. <title>Test upload</title>  
  4. </head>  
  5. <body>  
  6.    <form enctype="multipart/form-data" action="/upload.so" method="post">  
  7. <input type="hidden" name="test" value="上传">  
  8.   
  9.     选择文件1:  
  10.     <input type="file" name="filename1" />  
  11.     <br />  
  12.     选择文件2:  
  13.     <input type="file" name="filename2" />  
  14.     <br />  
  15.     选择文件3:  
  16.     <input type="file" name="filename3" />  
  17.     <br />  
  18.     <input type="submit" value="上载" />  
  19.    </form>  
  20. </body>  


2.添加一个Servlet.修改web.xml
Java代码  收藏代码
  1. <servlet>  
  2.      <servlet-name>upload</servlet-name>  
  3.      <servlet-class>com.XXX.servlet.Upload</servlet-class>  
  4.    </servlet>  
  5.     <servlet-mapping>  
  6.      <servlet-name>upload</servlet-name>  
  7.      <url-pattern>/upload.so</url-pattern>  
  8.    </servlet-mapping>  


3.编写Servlet,
将file的信息封装到upFiles的map中。
页面的其他信息(如:test),封装到agrs的map中
Java代码  收藏代码
  1. package com.XXXX.web.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.lang.reflect.Method;  
  5. import java.text.MessageFormat;  
  6. import java.util.HashMap;  
  7. import java.util.Map;  
  8.   
  9. import javax.servlet.ServletContext;  
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.ServletInputStream;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15.   
  16. import org.apache.commons.logging.Log;  
  17. import org.apache.commons.logging.LogFactory;  
  18. import org.springframework.web.context.WebApplicationContext;  
  19. import org.springframework.web.context.support.WebApplicationContextUtils;  
  20.   
  21. import com.XXXX.model.UpFile;  
  22. import com.XXXX.UploadManager;  
  23.   
  24. /** 
  25.  * @author winston 
  26.  *  
  27.  */  
  28. public class Upload  extends HttpServlet{  
  29.   
  30.     private final Log log = LogFactory.getLog(Upload.class);  
  31.       
  32.     private Map<String, UpFile> upFiles = new HashMap<String, UpFile>();  
  33.       
  34.     private Map<String, String> agrs = new HashMap<String, String>();  
  35.       
  36.     private ServletInputStream sis = null; //  
  37.       
  38.     private byte[] b = new byte[4096]; //  
  39.       
  40.     private static String rturl = "http://XXXXXX/ok.html";  
  41.       
  42.     public static final String  FILE_NAME="filename";  
  43.       
  44.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  45.             throws ServletException, IOException {  
  46.   
  47.          ServletContext application = getServletContext();    
  48.          WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);//获取spring的context    
  49.          UploadManager uploadManager = (UploadManager) wac.getBean("uploadManager");    
  50.           
  51.         sis = request.getInputStream();  
  52.         int a = 0;  
  53.         int k = 0;  
  54.         String s = "";  
  55.         while ((a = sis.readLine(b, 0, b.length)) != -1) {  
  56.             s = new String(b, 0, a);  
  57.               
  58.             if ((k = s.indexOf("name=\"")) != -1) {  
  59.                 String fieldName = s.substring(k + 6, s.length() - 3);  
  60.                 sis.readLine(b, 0, b.length);  
  61.                 StringBuffer fieldValue = new StringBuffer(b.length);  
  62.                 while ((a = sis.readLine(b, 0, b.length)) != -1) {  
  63.                     s = new String(b, 0, a - 2);  
  64.                     if ((b[0] == 45) && (b[1] == 45) && (b[2] == 45)  
  65.                             && (b[3] == 45) && (b[4] == 45)) {  
  66.                         break;  
  67.                     } else {  
  68.                         fieldValue.append(s);  
  69.                     }  
  70.                 }  
  71.   
  72.                   
  73.                 if(fieldName.startsWith(FILE_NAME)){  
  74.                     setField(fieldName, fieldValue.toString());  
  75.                 }else{  
  76.                     agrs.put(fieldName, fieldValue.toString());  
  77.                 }  
  78.                   
  79.                   
  80.                   
  81. //              fields.put(fieldName, fieldValue.toString());  
  82.             }  
  83.         }  
  84.           
  85.   
  86.         //业务处理  
  87.         uploadManager.saveUpload(upFiles, agrs);  
  88.           
  89.         response.sendRedirect(rturl);  
  90.     }  
  91.       
  92.     private void setField(String file_name, String file_value){  
  93.   
  94.         String[] str = file_name.split("\\.");  
  95.         UpFile upFile = null;  
  96.         if(upFiles.containsKey(str[0])){  
  97.             upFile = upFiles.get(str[0]);              
  98.         }else{  
  99.             upFile = new UpFile();  
  100.         }  
  101.           
  102.         String fieldName = str[1];  
  103.         String value = file_value;  
  104.           
  105.         String setMethodName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);  
  106.           
  107.           
  108.         try {  
  109.             Method setMethod = upFile.getClass().getMethod(setMethodName, String.class);  
  110.             if (value != null) {  
  111.                 setMethod.invoke(upFile, value);  
  112.             }  
  113.         } catch (Exception e) {  
  114.             e.printStackTrace();  
  115.             log.error(MessageFormat.format("Could not set ''{0}.{1} with value {2}",  
  116.                     upFile, fieldName, value));  
  117.         }  
  118.           
  119.         upFiles.put(str[0], upFile);  
  120.     }  
  121.   
  122. }  


2。对应nginx传递的参数,封装的对象
Java代码  收藏代码
  1. package com.XXX.model;  
  2.   
  3. import org.apache.commons.lang.builder.ToStringBuilder;  
  4. import org.apache.commons.lang.builder.ToStringStyle;  
  5. import org.apache.commons.lang.builder.EqualsBuilder;  
  6. import org.apache.commons.lang.builder.HashCodeBuilder;  
  7.   
  8. public class UpFile {  
  9.   
  10.     private String name;  
  11.       
  12.     private String content_type;  
  13.       
  14.     private String path;  
  15.       
  16.     private String crc32;  
  17.       
  18.     private String size;  
  19.   
  20.     public String getName() {  
  21.         return name;  
  22.     }  
  23.   
  24.     public void setName(String name) {  
  25.         this.name = name;  
  26.     }  
  27.   
  28.     public String getContent_type() {  
  29.         return content_type;  
  30.     }  
  31.   
  32.     public void setContent_type(String content_type) {  
  33.         this.content_type = content_type;  
  34.     }  
  35.   
  36.     public String getPath() {  
  37.         return path;  
  38.     }  
  39.   
  40.     public void setPath(String path) {  
  41.         this.path = path;  
  42.     }  
  43.   
  44.     public String getCrc32() {  
  45.         return crc32;  
  46.     }  
  47.   
  48.     public void setCrc32(String crc32) {  
  49.         this.crc32 = crc32;  
  50.     }  
  51.   
  52.     public String getSize() {  
  53.         return size;  
  54.     }  
  55.   
  56.     public void setSize(String size) {  
  57.         this.size = size;  
  58.     }  
  59.       
  60.     public String toString() {  
  61.         return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)  
  62.                 .append("name", this.name)  
  63.                 .append("content_type", this.content_type)  
  64.                 .append("path", this.path)  
  65.                 .append("crc32", this.crc32)  
  66.                 .append("size", this.size)  
  67.                 .toString();  
  68.     }  
  69.   
  70.     /** 
  71.      * @see java.lang.Object#equals(Object) 
  72.      */  
  73.     public boolean equals(Object object) {  
  74.         if (!(object instanceof UpFile)) {  
  75.             return false;  
  76.         }  
  77.         UpFile rhs = (UpFile) object;  
  78.         return new EqualsBuilder().appendSuper(super.equals(object)).append(  
  79.                 this.content_type, rhs.content_type)  
  80.                 .append(this.size, rhs.size).append(this.path, rhs.path)  
  81.                 .append(this.crc32, rhs.crc32).append(this.name, rhs.name)  
  82.                 .isEquals();  
  83.     }  
  84.   
  85.     /** 
  86.      * @see java.lang.Object#hashCode() 
  87.      */  
  88.     public int hashCode() {  
  89.         return new HashCodeBuilder(-404694209, 2059458549).appendSuper(  
  90.                 super.hashCode()).append(this.content_type).append(this.size)  
  91.                 .append(this.path).append(this.crc32).append(this.name)  
  92.                 .toHashCode();  
  93.     }  
  94.       
  95.       
  96. }  


3.业务处理uploadManager就按自己的需求写就可以了


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多