JAVA的文件上傳,比較經常使用的,仍是記錄一下。html
1、環境前端
J2EE,Mabitis與Spring框架,所需jar包:java
commons-io-1.2.jarweb
commons-fileupload-1.1.1.jarspring
2、代碼
後端
前端代碼安全
前端form中必須加上這一段enctype="multipart/form-data"服務器
提交方式必須是"post"框架
<form action="/upload.frm?method=upload" method="post" name="myform" id="myform" enctype="multipart/form-data"> <input type="file" name="file_upload"> <input type="submit" id="savebutton" value="提交" class="button_save"> </form>
配置文件ide
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- set fileUpload max size is 100MB --> <property name="maxUploadSize"> <value>104857600</value> </property> </bean>
後端代碼
上傳路徑最好放在WEB-INF下確保安全
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 獲得上傳的文件,file_upload對應前端代碼中file組件的name MultipartFile mFile = multipartRequest.getFile("file_upload"); // 獲得上傳服務器的路徑 String path = request.getSession().getServletContext() .getRealPath("/WEB-INF/upload/"); // 獲得上傳的文件的文件名 String filename = mFile.getOriginalFilename(); InputStream inputStream = mFile.getInputStream(); byte[] b = new byte[1048576]; int length = inputStream.read(b); path += "\\" + filename; // 文件流寫到服務器端 FileOutputStream outputStream = new FileOutputStream(path); outputStream.write(b, 0, length); inputStream.close(); outputStream.close();