圖片檔案上傳示例
阿新 • • 發佈:2018-10-31
程式碼片段:
//新增post @RequestMapping(method=RequestMethod.POST, value="/addPost") @ResponseBody public int addPost(Post post, MultipartFile file, HttpSession session) { try { if(file.getSize() > 0) { String path = session.getServletContext().getRealPath("upload/postImg/");//絕對路徑 System.out.println(path); File targetFile = new File(path, file.getOriginalFilename()); file.transferTo(targetFile); String p = path+file.getOriginalFilename(); System.out.println(p); post.setPostImg(file.getOriginalFilename()); System.out.println(post.getPostImg()); System.out.println(post); } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(post); return this.postService.addPost(post); }
springmvc-config.xml配置:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 配置包掃描器,掃描@Controller註解的類 --> <context:component-scan base-package="com.book.controller" /> <!-- 載入註解驅動 --> <mvc:annotation-driven /> <!-- 註冊介面卡 --> <!-- 配置檢視解析器 --> <!-- 訪問靜態檔案 --> <mvc:annotation-driven /> <mvc:resources location="/upload/" mapping="/upload/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/css/" mapping="/css/**"/> <!-- 支援檔案上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="104857600" /> <property name="maxInMemorySize" value="4096" /> <property name="defaultEncoding" value="UTF-8"></property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
本例用到了SSM框架知識,不懂得朋友可以先去了解SSM的相關知識,往後我會補上SSM的整個詳細搭建流程。