基於SpringMvc圖片上傳
阿新 • • 發佈:2018-01-26
contex tex 需要 rop int https ppi quest 文件大小
1.導入jar包(m)
<!-- 文件上傳組件 不同的版本號--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency>
2.導入包之後,需要配置SpringMVC文件上傳解析器,在Springmvc配置文件裏配置如下。
<!-- 文件上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大允許上傳文件大小,單位byte --> <property name="maxUploadSize" value="100000000"/> </bean>
3.編寫JSP代碼如下:
<form action="/springmvc01/upload/image.shtml" method="post" enctype="multipart/form-data"> <input type="file" name="userimage" /> <button>提交</button> </form>
4.編寫後臺代碼:
/*** * 文件上傳 * @param session * @param file * @param model * @return * @throws IllegalStateException * @throws IOException */ @RequestMapping(value="/image",method=RequestMethod.POST) public String upload(HttpSession session,@RequestParam(value="userimage")MultipartFile file,Model model) throws IllegalStateException, IOException{ //文件上傳路徑 String path = session.getServletContext().getRealPath("/upload"); //文件名字 String fname = (int)(Math.random()*10000)+file.getOriginalFilename(); file.transferTo(new File(path+"/"+fname)); //文件訪問路徑 String fileurl = "/upload/"+fname; model.addAttribute("fileurl", fileurl); return "hello"; }
基於SpringMvc圖片上傳