关于springmvc上传图片的方法小编给大家整理了两种方法,具体内容如下所示:
第一种:(放在该项目下的物理地址对应的位置)
a. 路径写法:
String basePath="/WEB-INF/resources/upload";
String filePathName= request.getSession().getServletContext().getRealPath(basePath);存放路径
b. 实际路径:
D:\WorkSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\XYT\WEB-INF\resources\upload\图片名称
c. 访问路径: http://localhost:8080/XYT/resources/upload/图片名称
d. 前提:只要这个项目能运行就行。
第二种:(创建虚拟路径,配置Tomcat下server.xml,创建存储路径和访问路径)
1.路径写法:
String filePathName=Constant.IMG_PATH+File.separator+"upload";
其中:public static final String IMG_PATH = "E:\\Java\\img";
2.路径配置:
Server.xml配置
unpackWARs="true" autoDeploy="true">
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
3.实际路径:E:\Java\img\upload
6.前提:必须打开Tomcat服务器
举例:上传图片的实例:(可以上传多张图片)
JSONObject rs=new JSONObject();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
String url="";
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile((String) iter.next());
if (file != null) {
String originalFileName = file.getOriginalFilename();
String[] f = originalFileName.split("\\.");
String ext = "";
if(f!=null && f.length>1){
ext = f[f.length-1];
System.out.println(ext);
}
System.out.println(allowImgType==null);
if(!allowImgType.contains(ext.toUpperCase())){
rs.put("code", "ERR_UPLOAD_0003");
rs.put("msg", "类型错误");
return rs;
}
//String basePath="/WEB-INF/resources/upload";//String filePathName = request.getSession().getServletContext().getRealPath(basePath);
String filePathName=Constant.IMG_PATH+File.separator+"upload";
url = filePathName;
System.out.println(url);
//上传后记录在path这个路径下。
File localFile = new File(filePathName);
if(!localFile.exists()){
localFile.mkdir();
}
//compress
String fname =new Date().getTime()+"."+ext;
String originalFname = fname.substring(0,fname.indexOf("."))+"_original."+ext;
String fileName = filePathName + File.separator + fname;
String oFileName = filePathName + File.separator + originalFname;
File infile = new File(fileName);
File oFile = new File(oFileName);
try{
ImageHelper.compress(file.getInputStream(), 600, infile);
file.transferTo(oFile);//original 上传原图
JSONObject obj = new JSONObject();
rs.put("code", Constant.CODE_SUCCESS);
rs.put("data", obj.toString());
}catch(Exception e){
rs.put("code", "ERR_UPLOAD_0001");
rs.put("msg", "ERR_UPLOAD_0001");
e.printStackTrace();
return rs;
}
}
以上所述是针对SpringMVC上传图片与访问的相关内容,希望对大家有所帮助。