web端上传图片的几种方式

来源:互联网 发布:儿童生长曲线软件 编辑:程序博客网 时间:2024/06/05 21:34

首先是后台要有一个上传图片的工具类:

[java] view plain copy
  1. package utils;  
  2.   
  3. import java.io.File;  
  4.   
  5. import org.apache.commons.lang.StringUtils;  
  6.   
  7. import play.Logger;  
  8. import play.Play;  
  9.   
  10. import com.google.gson.Gson;  
  11. import com.ning.http.client.AsyncHttpClient;  
  12. import com.ning.http.client.Response;  
  13. import com.ning.http.multipart.FilePart;  
  14. import com.ning.http.multipart.StringPart;  
  15.   
  16. public class PictureUploadUtils {  
  17.   
  18.     public static String PICTURE_SERVER = Play.configuration.getProperty(  
  19.             "pic.host""http://oss.iclass.cn/form");  
  20.     public static String PICTURE_SERVER_BASEURL = "http://oss.iclass.cn/smallfiles";  
  21.   
  22.     private class Result {  
  23.         public boolean succ;  
  24.         public String html;  
  25.     }  
  26.   
  27.     public class InfoResult {  
  28.         public int width;  
  29.         public int height;  
  30.     }  
  31.   
  32.     public static String getUrlFromServer(File file) {  
  33.         final AsyncHttpClient client = new AsyncHttpClient();  
  34.         try {  
  35.             final Response response = client.preparePost(PICTURE_SERVER)  
  36.                     .addBodyPart(new FilePart("qqfile", file))  
  37.                     .addBodyPart(new StringPart("bucketName""smallfiles"))  
  38.                     .addBodyPart(new StringPart("source""WEB")).execute()  
  39.                     .get();  
  40.             final String responseBody = response.getResponseBody("utf8");  
  41.             if (responseBody == null) {  
  42.                 Logger.error("[EndServer has not started.]");  
  43.             } else {  
  44.                 Result result = new Gson().fromJson(responseBody, Result.class);  
  45.                 return result.html;  
  46.             }  
  47.         } catch (Exception e) {  
  48.             Logger.error(e, e.getMessage());  
  49.         } finally {  
  50.             client.close();  
  51.         }  
  52.         return "";  
  53.     }  
  54.   
  55.     public static InfoResult getInfoFromServer(String url) {  
  56.         final AsyncHttpClient client = new AsyncHttpClient();  
  57.         try {  
  58.             final Response response = client.prepareGet(url + "/info")  
  59.                     .execute().get();  
  60.             final String responseBody = response.getResponseBody("utf8");  
  61.             if (responseBody == null) {  
  62.                 Logger.error("[EndServer has not started.]");  
  63.             } else {  
  64.                 return new Gson().fromJson(responseBody, InfoResult.class);  
  65.             }  
  66.         } catch (Exception e) {  
  67.             Logger.error(e, e.getMessage());  
  68.         } finally {  
  69.             client.close();  
  70.         }  
  71.         return null;  
  72.     }  
  73.   
  74.     public enum Effect {  
  75.         PURE {// 原图  
  76.             @Override  
  77.             public String toString() {  
  78.                 return "";  
  79.             }  
  80.         },  
  81.         FILL {// 填充  
  82.             @Override  
  83.             public String toString() {  
  84.                 return "f";  
  85.             }  
  86.         },  
  87.         CUT {// 裁剪  
  88.             @Override  
  89.             public String toString() {  
  90.                 return "c";  
  91.             }  
  92.         };  
  93.         @Override  
  94.         abstract public String toString();  
  95.     }  
  96.   
  97.     public static boolean isFromPicServer(String picUrl) {  
  98.         return StringUtils.startsWithIgnoreCase(picUrl, PICTURE_SERVER_BASEURL);  
  99.     }  
  100.   
  101.     /** 
  102.      * @author xz8885 获取指定大小图片的方法,当宽或高为零时为零的维度会等比缩放,均为0则返回原始图片 
  103.      * 
  104.      * @param width 
  105.      * @param height 
  106.      * @param defaultUrl 
  107.      * @return 图片url 
  108.      */  
  109.     public static String getPictureFromPicServer(int width, int height,  
  110.             Effect effect, String defaultUrl) {  
  111.         if (!isFromPicServer(defaultUrl)) {  
  112.             return defaultUrl;  
  113.         }  
  114.         String fileName = StringUtils.substringAfterLast(defaultUrl, "/");  
  115.         effect = effect == null ? Effect.PURE : effect;  
  116.         return PICTURE_SERVER_BASEURL + "/" + width + "_" + height  
  117.                 + effect.toString() + "/" + fileName;  
  118.     }  
  119. }  

一、使用ajax上传

js代码如下:

[javascript] view plain copy
  1. var upload = $("#uploadInput");  
  2. $("#uploadImg").click(function(){  
  3. <span style="white-space:pre">    </span>if($("#picNum").html()<5){  
  4.         upload.click();  
  5.     }else{  
  6.         alert( '已达到可上传图片数量上限');  
  7.         return;  
  8.     }  
  9. });  
  10. upload.change( function(){  
  11.     var formData = new FormData($("#uploadForm")[0]);  
  12.          $.ajax({  
  13.         <span style="white-space:pre">    </span> url: '/assist/upload',  
  14.              type: 'POST',  
  15.              data: formData,  
  16.              async: false,  
  17.              cache: false,  
  18.              contentType: false,  
  19.              processData: false,  
  20.              success: function (json) {  
  21.             <span style="white-space:pre">    </span>var url=json.data;  
  22.             <span style="white-space:pre">    </span>var str = '<li class="pic"><img src="'+url+'"><span class="pic-bg"></span><a href="javascript:;" class="picDelete pic-del">×</a></li>'  
  23.             <span style="white-space:pre">    </span>$("#uploadImg").parent().before(str);  
  24.             <span style="white-space:pre">    </span>$("#uploadInput").val("");  
  25.             <span style="white-space:pre">    </span>var num=Number($("#picNum").html())+1;  
  26.             <span style="white-space:pre">    </span>$("#picNum").html(num);  
  27.         <span style="white-space:pre">    </span> },  
  28.              error: function (json) {  
  29.                  alert(json);  
  30.                                 }  
  31.               });  
  32.         });  

对应的controller中方法:
[java] view plain copy
  1. public static void upload(File file, String fileType) {  
  2.         String url = "";  
  3.         String pathname = file.getAbsolutePath().replaceAll(" ""_");  
  4.         File newFile = new File(pathname);  
  5.         file.renameTo(newFile);  
  6.         url = PictureUploadUtils.getUrlFromServer(newFile);  
  7.           
  8.     }  

二、使用upload.js上传

upload.js 代码:

[javascript] view plain copy
  1. /** 
  2.  * jQuery upload v1.2 
  3.  * http://www.ponxu.com 
  4.  * 
  5.  * @author xwz 
  6.  */  
  7. (function($) {  
  8.     var noop = function(){ return true; };  
  9.     var frameCount = 0;  
  10.       
  11.     var uploadDefault = {  
  12.         url: '',  
  13.         fileName: 'filedata',  
  14.         dataType: 'json',  
  15.         params: {},  
  16.         onSend: noop,  
  17.         onComplate: noop  
  18.     };  
  19.   
  20.     $.upload = function(options) {  
  21.         var opts = $.extend(uploadDefault, options);  
  22.         if (opts.url == '') {  
  23.             return;  
  24.         }  
  25.           
  26.         var canSend = opts.onSend();  
  27.         if (!canSend) {  
  28.             return;  
  29.         }  
  30.         var vcount=++frameCount;  
  31.         var frameName = 'upload_frame_' + vcount;  
  32.         var iframe = $('<iframe style="position:absolute;top:-9999px" />').attr('name', frameName);  
  33.         var form = $('<form id="formUpload_'+vcount+'" method="post" class="abs_out" enctype="multipart/form-data" />').attr('name''form_' + frameName).attr("target", frameName).attr('action', opts.url);  
  34.         // form中增加数据域  
  35.         var formHtml = '<input type="file" id="formUpload_file_'+vcount+'" name="' + opts.fileName + '" onchange="onChooseFile(this)">';  
  36.         form.append(formHtml);  
  37.         iframe.appendTo("body");  
  38.         form.appendTo("body");  
  39.         // iframe 在提交完成之后  
  40.         iframe.load(function() {  
  41.             var contents = $(this).contents().get(0);  
  42.             var data = $(contents).find('body').text();  
  43.             if ('json' == opts.dataType) {  
  44.                 var data1 = eval('(' + data + ')');  
  45.             }  
  46.               
  47.             opts.onComplate(data1);  
  48.             setTimeout(function() {  
  49.                 iframe.remove();  
  50.                 form.remove();  
  51.             }, 5000);  
  52.         });  
  53.           
  54.         // 文件框  
  55. //      alert($("#formUpload").attr("action"));  
  56.         $("#formUpload_"+vcount).children("input").click();  
  57.     };  
  58. })(jQuery);  
  59.   
  60. // 选中文件, 提交表单(开始上传)  
  61. var onChooseFile = function(fileInputDOM) {  
  62.     var form = $(fileInputDOM).parent();  
  63.     form.submit();  
  64.       
  65. };  

对应的js代码:
[javascript] view plain copy
  1. //附件上传  
  2.         var upload=function(options){  
  3.             Do('upload',function(options){  
  4.                 $.upload({  
  5.                     // 上传地址  
  6.                     url: '/upload',   
  7.                     // 文件域名字  
  8.                     fileName: 'filedata',   
  9.                     // 其他表单数据  
  10.                     params: {name: 'pxblog'},  
  11.                     // 上传完成后, 返回json, text  
  12.                     dataType: 'json',  
  13.                     // 上传之前回调,return true表示可继续上传  
  14.                     onSend: function() {      
  15.                         return true;  
  16.                     },  
  17.                     // 上传之后回调  
  18.                     onComplate: function(json) {  
  19.                         var path= json.data;  
  20.                         alert(path);  
  21.                     }  
  22.                 });  
  23.             });  
  24.         }  
  25.         var uploadPic=function(){  
  26.             $("#uploadPicBtn").click(function(){  
  27.                 var ele=$(this);  
  28.                 upload(ele);  
  29.             })  
  30.         }  
  31.         uploadPic();  

对应的controller方法:
[java] view plain copy
  1. public static void upload() throws Exception {  
  2.         DataParser parser = DataParser.parsers.get(request.contentType);  
  3.         parser.parse(request.body);  
  4.         ArrayList<FileUpload> uploads = (ArrayList<FileUpload>) request.args  
  5.                 .get("__UPLOADS");  
  6.         String fileName = "";  
  7.         for (FileUpload upload : uploads) {  
  8.             if (upload.getFileName().endsWith(".mp4")) {  
  9.                 fileName = AudioUploadUtils.getUrlFromServer(upload.asFile());  
  10.             } else {  
  11.                 fileName = PictureUploadUtils.getUrlFromServer(upload.asFile());  
  12.             }  
  13.             // break;  
  14.         }  
  15.           
  16.     } 
原创粉丝点击