Spring mvc图片上传

1、导入js
jquery.easyui.min.js,
jquery.min.js,
talent-validate-all.js,
easyui.css,
demo.css,
icon.css,
popup.css,
jquery-1.8.0.min.js,
jquery.easyui.min.js
2、 js代码片段

<script type="text/javascript"> /** * 创建上传窗口 公共方法 * @param chunk 是否分割大文件 * @param callBack 上传成功之后的回调 */ function Uploader(uploadFileCount,chunk,callBack){ var addWin = $('<div style="overflow: hidden;"/>'); var upladoer = $('<iframe/>'); upladoer.attr({'src':'${basePath}core/pages/business/uploader.jsp?chunk='+chunk+'&uploadFileCount='+uploadFileCount,width:'100%',height:'100%',frameborder:'0',scrolling:'no'}); addWin.window({ title:"上传文件", height:450, width:650, minimizable:false, modal:true, collapsible:false, maximizable:false, resizable:false, content:upladoer, onClose:function(){ var fw = GetFrameWindow(upladoer[0]); var files = fw.files; $(this).window('destroy'); callBack.call(this,files); }, onOpen:function(){ var target = $(this); setTimeout(function(){ var fw = GetFrameWindow(upladoer[0]); fw.target = target; },100); } }); } /** * 根据iframe对象获取iframe的window对象 * @param frame * @returns {Boolean} */ function GetFrameWindow(frame){ return frame && typeof(frame)=='object' && frame.tagName == 'IFRAME' && frame.contentWindow; } function makerUpload(chunk){ var uploadFileCount=1; Uploader(uploadFileCount,chunk,function(files){ if(files && files.length>0) { // for (var i=0;i<files.length;i++) for (var i=0;i<1;i++) { var image=$("<div class='div-inline' ><img class='photo' src='${basePath}upload/"+files[i]+"' filename='"+ files[i] +"'/>"+ "<a href='javascript:' onclick='deletePhoto(this)'>删除</a></div>"); $("#res").append(image); } } }); } function deletePhoto(obj) { $("#cmImgUrls").val(''); $("#res").text(''); } </script>
<script type="text/javascript"> function validateForm(){ var formName = 'form1'; var isValid = true; var jsonStr=""; $("#res div img").each(function(k,v){ jsonStr = jsonStr + $(v).attr("filename"); if ($("#res div img").size()-1 !=k) { jsonStr=jsonStr; } }); $("#cmImgUrls").val(jsonStr); if(isValid){ var cmtypename=$("#cmtypename").val(); if(cmtypename==null||cmtypename==""){ alert("商铺名不能为空"); return; } ajaxSubmitForm(formName,2000); return true; } } </script>

3、form表单代码片段

 <form id="form1" action="${basePath}CommodityController/addCMTypes.do" method="post">
 <tr>
  <td align="right" height="150">


    <h3><a class="easyui-linkbutton" href="javascript:makerUpload(false)">商品图片文件上传</a></h3>
                       <input type="hidden" id="cmImgUrls" name="cmtypeimgurl" value="${CommodityType.cmtypeimgurl}">   


             <div id="res">
              </div>
         </td>
 </tr>
 <tr>
                 <td align="right">
                    <a href="javascript:;" class="operation btn_close border" onclick="closeDiv(frameElement);">关闭</a>
                 </td>
                 <td width="30"></td>
                <td align="left">
                    <a href="javascript:;" class="hcxpgbtnr border" onclick="validateForm()">确定</a>
                </td>
           </tr>         
 </form>

4、xml配置片段:

<bean id="uploadProperty" class="com.common.core.upload.model.UploadProperty">
        <property name="savePath" value="../upload/" />
        <property name="contextUploadPath" value="http://localhost/secp/upload/"></property>
</bean>

5、Java代码片段:

package com.application.action.business;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.common.context.Environment;
import com.common.core.upload.model.UploadProperty;

/* * 本文件为运营后台 和 前端手机 服务 */
@Controller
@RequestMapping(value = "/")
public class ImageController {

    private static final int BUFFER_SIZE = 100 * 1024;
    private static final Logger logger = Logger.getLogger(ImageController.class);
    @Autowired
    UploadProperty uploadProperty;

    /** * 使用plupload上传文件 * @param file 文件对象 * @param name 文件名称 * @param chunk 数据块序号 * @param chunks 数据块总数 * @return */
    @RequestMapping("/ImageController/uploader")
    public void fileupload(HttpServletRequest request,HttpServletResponse response,HttpSession session) {

        String realPath = session.getServletContext().getRealPath("");
        String UPLOADDIR=realPath+Environment.getEnvironment().getConfigProperties()
                .getProperty("upload.savepath"); 
         InputStream  inputStream=null; 
            FileOutputStream outputStream=null; 
            String newFileName="";
            String newFileFullPathName="";
            MultipartHttpServletRequest multiReq =null;
            HashMap<String, MultipartFile>  hashMap = null;

         try { 
             multiReq = (MultipartHttpServletRequest) request; 
              hashMap=(HashMap<String, MultipartFile>) multiReq.getFileMap(); 


            for (Entry<String,MultipartFile> entry : hashMap.entrySet()) {  
                MultipartFile  file = entry.getValue(); 
                inputStream =  file.getInputStream(); 
                File  fileDir= new File(UPLOADDIR); 
                if(!fileDir.exists()||!fileDir.isDirectory()){  
                    fileDir.mkdir(); 
                }  
                newFileName =System.currentTimeMillis()+file.getOriginalFilename() ;
                newFileFullPathName = UPLOADDIR+"/"+newFileName;
                File uploadFile= new File(newFileFullPathName); 
                if(uploadFile.exists()){  
                    uploadFile.delete(); 
                }  
                uploadFile.createNewFile(); 
                outputStream  =new FileOutputStream(uploadFile); 
                byte[]  bs =  new byte[1024]; 
                int len=0; 
                while ((len=inputStream.read(bs))>0) {  
                    outputStream.write(bs); 
                }  
               // System.out.println(file.getOriginalFilename()+"上传成功"); 
            } 
            response.getWriter().print("{\"status\":true,\"newName\":\""+newFileName+"\",\"photoPath\":\""+ Environment.getEnvironment().getConfigProperties()
                    .getProperty("upload.httpaddress") +"\"}");
            } catch (Exception e) {
                //e.printStackTrace();
                try {
                    response.getWriter().print("{\"status\":false}");
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    //e1.printStackTrace();
                }
            }finally{  
                try {  
                    if(outputStream!=null)
                        outputStream.close(); 
                } catch (IOException e) {  
                    e.printStackTrace(); 
                }  
            }   

    }

    private void appendFile(InputStream in, File destFile) {
        OutputStream out = null;
        try {
            // plupload 配置了chunk的时候新上传的文件append到文件末尾
            if (destFile.exists()) {
                out = new BufferedOutputStream(new FileOutputStream(destFile, true), BUFFER_SIZE); 
            } else {
                out = new BufferedOutputStream(new FileOutputStream(destFile),BUFFER_SIZE);
            }
            in = new BufferedInputStream(in, BUFFER_SIZE);

            int len = 0;
            byte[] buffer = new byte[BUFFER_SIZE]; 
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {     
            try {
                if (null != in) {
                    in.close();
                }
                if(null != out){
                    out.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }

}

你可能感兴趣的:(上传)