首页 > 代码库 > springMVC 获取本地项目路径 以及上传文件的方法整理

springMVC 获取本地项目路径 以及上传文件的方法整理

String path=request.getSession().getServletContext().getRealPath("upload/img/product");

//二进制上传
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//获取文件
CommonsMultipartFile fpic=(CommonsMultipartFile) multipartRequest.getFile("fpic");
//判断是否有文件提交
if(fpic!=null){
if(!fpic.isEmpty()){
    String time=DataUtil.getCurrentTimeMillis();
    String path=request.getSession().getServletContext().getRealPath("upload/img/product");
    File file = new File(path+"/"+time+ ".jpg");
    fpicurl = "upload/img/product/p"+time+".jpg";
    try {
         fpic.getFileItem().write(file);
    } catch (Exception e) {
         e.printStackTrace();
         return;
    }
}
}



需要工具包

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

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

import java.io.File;
import java.io.IOException;

import com.realgo.util.DataUtil;


class DataUtil

	public static String getCurrentTimeMillis(){
		return String.valueOf(System.currentTimeMillis());
	}