spring下Ajax上传图片

package com.bigdata.report.controller;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;


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


import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 com.bigdata.report.util.DateUtil;


/**
 * 图片上传控制类
 * @ClassName: XHEditorPicUploadController
 * @author dxh
 * @Company: <p>www.bigdata.com</p>
 * @date 2018年4月24日14:24:04
 */
@Controller
@RequestMapping("/upload")
public class XHEditorPicUploadController extends BaseController {
private static final  Log logger = LogFactory.getLog(XHEditorPicUploadController.class);
/**
* 上传图片
* @return
* @throws Exception 
*/
     @RequestMapping(value = "/image",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
     @ResponseBody
     public String image(HttpServletRequest request,HttpSession session,@RequestParam("filedata") MultipartFile file) {
         // 将图片按日期分开存放,方便管理
         final String prefix = "upload/images/"+ DateUtil.format(new Date(), "yyyy-mm-dd");
         // 存放到web根目录下,如果日期目录不存在,则创建,
         // 注意 request.getRealPath("/") 已经标记为不推荐使用了.
         final String realPath = session.getServletContext().getRealPath(prefix);
         logger.info(realPath);
         File dir = new File(realPath);
         if(!dir.exists()) {
             dir.mkdirs();
         }
         // 以下是真正的上传部分
         String error = "";
         // 取得原文件名
         String originName = file.getOriginalFilename();
         // 取得文件后缀
         String fileExt = originName.substring(originName.lastIndexOf(".") + 1);
         // 按时间戳生成图片文件名
         String picture = DateUtil.format(new Date(), "yyyymmdd") + "."+ fileExt;
         try{
             IOUtils.copy(file.getInputStream(),new FileOutputStream(new File(dir, picture)));
         }catch(Exception e) {
             logger.error("error:", e);
             error = e.getMessage();
         }
         String http = "http://"+ request.getServerName()+":" + request.getServerPort()+ request.getContextPath();  
         String url =  http + "/"+ prefix + "/"+ picture;
         //注意这里的格式(见xheditor文档)
         //{'err':'',msg:{'url':'XXX/upload/images/2012/11_11/20121111015039.jpg','localname':'我的头像.jpg','id':'63'}}
         String json = String.format("{'err':'%s',msg:{'url':'%s','localname':'%s','id':'%s'}}",error, url, originName, 1);
         return json;
     }
}

猜你喜欢

转载自blog.csdn.net/rentian1/article/details/80064617