1. 程式人生 > >使用fckeditor上傳多張圖片

使用fckeditor上傳多張圖片

流程:

1.使用fck上傳圖片到後臺

2.後臺上傳圖片到伺服器端

3.伺服器端返回上傳資訊

1.jsp頁面

<script type="text/javascript">
$(function(){
    var tObj;
    $("#tabs a").each(function(){
        if($(this).attr("class").indexOf("here") == 0){tObj = $(this)}
        $(this).click(function(){
            var c = $(this).attr("class
"); if(c.indexOf("here") == 0){return;} var ref = $(this).attr("ref"); var ref_t = tObj.attr("ref"); tObj.attr("class","nor"); $(this).attr("class","here"); $(ref_t).hide(); $(ref).show(); tObj = $(this);
if(ref == '#tab_2'){ var fck = new FCKeditor("productdesc"); fck.BasePath = "/res/fckeditor/"; fck.Config["ImageUploadURL"] = "/upload/uploadFck.do"; fck.Height = 400 ; fck.ReplaceTextarea(); } }); }); });
function uploadPic(){ var options={ url:"/upload/uploadPic.do", dataType:"json", type:"post", success:function(data){ $("#product_url").attr("src",data.url); $("#imgUrl").val(data.path); } }; $("#jvForm").ajaxSubmit(options); } </script>
<tbody id="tab_2" style="display: none">
                <tr>
                    <td >
                        <textarea rows="10" cols="10" id="productdesc" name="description"></textarea>
                    </td>
                </tr>
</tbody>

2.controller層

 //非同步上傳沒有返回值
     @RequestMapping(value="/upload/uploadFck.do")
     public void uploadFck(HttpServletRequest request, HttpServletResponse response){
         MultipartHttpServletRequest ms = (MultipartHttpServletRequest) request;
         Map<String, MultipartFile> filemap = ms.getFileMap();
         Set<Entry<String,MultipartFile>> entrySet = filemap.entrySet();
         for (Entry<String, MultipartFile> entry : entrySet) {
             MultipartFile pic = entry.getValue();
             Client client = new Client();        
             ///圖片生成策略
             DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
             String format = df.format(new Date());
             Random r = new Random();
             for(int i = 0;i<3; i++){
                 format += r.nextInt(10);
             }
             //得到檔案擴張名
             String ext = FilenameUtils.getExtension(pic.getOriginalFilename());
             String path = "upload/"+format+"."+ext;
             String url = "http://localhost:8088/image-web/"+path; //伺服器路徑
             WebResource resource = client.resource(url);
             try {
                resource.put(String.class,pic.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            } 
             UploadResponse ok = UploadResponse.getOK(url);//ok是個物件
            try {
                response.getWriter().print(ok); //使用print可以返回物件
                //write 字元流
                //print 位元組流
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

     }