首页 > 代码库 > ajax异步上传图片&SpringMVC后台代码

ajax异步上传图片&SpringMVC后台代码

function uploadPic(){
	var options = {
			url : "/upload/updatePic.action",
			type : "post",
			dataType : "json",
			success : function(data){
				$("#allUrl").attr("src", data.url);
				$("#imgUrl").val(data.url);
			}
	};
	$("#jvForm").ajaxSubmit(options);
}

  

package top.dgoyou.core.controller;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/upload")
public class UploadController {
    
    //异步上传图片
    @RequestMapping("/updatePic")
    public void updatePic(MultipartFile pic,HttpServletResponse response) throws Exception{
        //获取文件原始名
        String filename = pic.getOriginalFilename();
        //使用随机字符串+ 源图片扩展名组成新的图片名称, 防止图片重名
        String newFileName=UUID.randomUUID().toString().replaceAll("-","")+"."+FilenameUtils.getExtension(filename);
        //将文件保存到图片服务器("E:\testpic"存放图片虚拟路径 后期可换成FastDFS||云端)
        pic.transferTo(new File("E:\testpic"));
        //JSONObject是简单的转json工具类 , 但是只可以转string, double,integer,long等简单类型, 不可以转pojo, list, set, map等
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url","/pic/"+ newFileName);
        response.setContentType("application/json;charset=utf-8");
     //响应到前台页面 response.getWriter().write(jsonObject.toString()); } }

 

ajax异步上传图片&SpringMVC后台代码