SpringMVC上传图片与访问
关于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配置
<host name="localhost" appbase="webapps" unpackwars="true" autodeploy="true"> <valve classname="org.apache.catalina.valves.accesslogvalve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t "%r" %s %b" /> <!-- add(save pictures) --> <context path="/upload" docbase="e:\java\img\upload"></context> </host>
3.实际路径:e:\java\img\upload
4.访问路径:图片名称
5.参考:
6.前提:必须打开tomcat服务器
举例:上传图片的实例:(可以上传多张图片)
jsonobject rs=new jsonobject(); commonsmultipartresolver multipartresolver = new commonsmultipartresolver( request.getsession().getservletcontext()); string url=""; if (multipartresolver.ismultipart(request)) { multiparthttpservletrequest multirequest = (multiparthttpservletrequest) request; iterator<string> 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上传图片与访问的相关内容,希望对大家有所帮助。
下一篇: jdbc连接oracle数据库功能示例