標籤:rac fileutil 原因 mem base64 filename array blog new
首先檔案的上傳只能使用表單提交的方式,其中需要幾個jar包 commons-io-1.3.2.jar,commons-fileupload-1.2.1jar,頁面的代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><script type="text/javascript"></script></head><body></head><body></div><form action="pp" enctype ="multipart/form-data" method="post"><input type="file" name="image"><input type="submit" value="提交"></form></body></html>
開發的架構使用的是springmvc架構
後端的代碼如下:
@RequestMapping(value="pp")public String reg5(@RequestParam("image") CommonsMultipartFile[] files,HttpServletRequest request){ String path = request.getContextPath(); String str =null; for(int i = 0;i<files.length;i++){ if(!files[i].isEmpty()){ str = request.getSession().getServletContext().getRealPath("/")+"fileUpload\\temp"+ new Date().getTime() + files[i].getOriginalFilename(); System.out.println(str); int pre = (int) System.currentTimeMillis(); String filename=files[i].getOriginalFilename(); try {
//這個工具類我就不提供了,就是把檔案寫入本地檔案。 FileUtils.writeByteArrayToFile(new File(str,filename), files[i].getBytes(),true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return "success";}
在springmvc架構中傳遞的檔案很大,可能會傳不過去,你可以在 spring的設定檔中加上一段配置。如下:
Required CommonsMultipartFile parameter ‘file‘ is not present
報這個錯的時候可以在項目中加一個配置,原因是位元組數太大
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="104857600" /> <property name="maxInMemorySize" value="4096" /> </bean>
其實這個檔案要是一個圖片,你要是想存在資料庫,可以把它產生一個base64的圖片,只是一段字串。。。。直接就可以儲存。
拿出來放在image標籤的src裡面就可以展示圖片了,但是像素可能會有影響,你可以在產生時設定一下。
如何產生base64圖片,我的部落格裡面會有單獨的說明。
java中檔案的上傳(簡單的操作)