1.首先上html的代码
Test.html上传图片
function change(){
var filePath = $("#file").val();
alert("filePath "+filePath);
var imgObj =$("#file")[0].files[0];
alert("imgObj "+imgObj);
//将formData传给后台
var formData=new FormData();
formData.append("file",imgObj);
alert("formData"+formData);
//ajax请求后台,将请求的数据调用fileUp接口并且填写上传的服务器地址savePath
$.ajax({
url: "http://192.168.1.107:8080/SellingTea/fileUp?savePath=uploadFiles/headPortrait",
type: "POST",
data: formData,
dataType:"json",
/**
*必须false才会自动加上正确的Content-Type
*/
contentType: false,
/**
* 必须false才会避开jQuery对 formdata 的默认处理
* XMLHttpRequest会对 formdata 进行正确的处理
*/
processData: false,
success: function (data) {
if(data){
alert("上传成功!");
console.log("data "+JSON.stringify(data));
$("#img").attr("src",data.path);
}
},
error: function () {
alert("上传失败!");
}
});
}
2.在看接口
3.接口内容
package com.st.controller.system;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.st.controller.base.BaseController;
import com.st.util.DateUtil;
/**
*
* @author wy
*
*/
@Controller
public class FileUpController extends BaseController {
Logger logger = Logger.getLogger(FileUpController.class.getName());
/**
* 处理文件上传
* @param response
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value="fileUp")
public void upload(HttpServletResponse response,HttpServletRequest request) throws IOException{
logger.info("处理文件上传");
response.setCharacterEncoding("utf-8");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map fileMap = multipartRequest.getFileMap();
//String savePath = this.getServletConfig().getServletContext().getRealPath("");
//savePath = savePath + "/uploads/";
// 文件保存路径 ctxPath本地路径
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
//String ymd = sdf.format(new Date()); +File.separator+"uploadFiles/czy"
String savefile = request.getParameter("savePath");
String replace = request.getParameter("replace");
String ctxPath=request.getSession().getServletContext().getRealPath("/");
String allpath = request.getRequestURL().toString();
String all[] = allpath.split("fileUp");
String currpath = all[0];
System.out.println("currpath="+currpath+savefile);
if("1".equals(replace)){//1替换项目名
String a= ctxPath.replace("SellingTea","productImg");
ctxPath =a;
System.out.println("路径1" + ctxPath);
}else{
ctxPath=request.getSession().getServletContext().getRealPath("/")+savefile+"\\";
}
// ctxPath=request.getSession().getServletContext().getRealPath("/")+File.separator+"uploadFiles/czy";
// ctxPath += File.separator + ymd + File.separator;
ctxPath += File.separator;
System.out.println("ctxpath="+ctxPath);
// 创建文件夹
File file = new File(ctxPath);
if (!file.exists()) {
file.mkdirs();
}
String fileName = null;
for (Map.Entry entity : fileMap.entrySet()) {
// 上传文件
MultipartFile mf = entity.getValue();
fileName = mf.getOriginalFilename();
//获取原文件名
System.out.println("filename="+fileName);
String realNmae=DateUtil.getDteStr()+"@"+ fileName;
File uploadFile = new File(ctxPath +realNmae);
try {
FileCopyUtils.copy(mf.getBytes(), uploadFile);
JSONObject json=new JSONObject();
json.put("sendName", fileName);
json.put("realNmae", realNmae);
json.put("path", currpath+savefile+"/"+realNmae);
System.out.println("path="+ctxPath+realNmae);
PrintWriter pw =response.getWriter();
pw.print(json);
pw.close();
System.out.println("上传成功");
} catch (IOException e) {
System.out.println("上传失败");
e.printStackTrace();
}
}
}
}
4.效果图