基於SpringMVC使用Fileupload上傳檔案
阿新 • • 發佈:2018-12-10
1 通過pom或者其他方式載入jar包,需要匯入兩個包。
2 注意spring-mvc.xml檔案要進行配置,配置如下:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3 然後就是前端程式碼了;注意型別就好了。
<form action="file/text" method="post" enctype="multipart/form-data"> <div class="col-md-6 col-sm-12"> <div class="block"> <div class="form-group"> <input id="file0" name="file0" type="file" multiple class="file" data-show-caption="true"> </div>
4 看後臺操作(使用IO)
public String text(@RequestParam(value = "file0",required = false) CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception { String filepath = request.getSession().getServletContext().getRealPath("");// 獲取請求檔案在伺服器下的路徑 // 為每個使用者(進行提交的)建立臨時唯一資料夾 File dir = new File(filepath + "/temporary"); if (!dir.exists()) { dir.mkdirs(); // 建立臨時資料夾 } String username = UUID.randomUUID().toString();// 建立全球唯一UUID; dir = new File(filepath + "/temporary/" + username); if (!dir.exists()) { dir.mkdirs(); // 建立使用者資料夾 } System.out.println("建立成功"+username); String ppath =filepath + "/temporary/" + username; try { // 獲取輸出流 OutputStream os = new FileOutputStream(ppath + "/test_file" + ".txt"); // 獲取輸入流CommonsMultipartFile中可以直接得到檔案的流 InputStream is = file.getInputStream(); int temp; // 一個一個位元組的讀取並寫入 while ((temp = is.read()) != (-1)) { os.write(temp); } os.flush(); os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); }