前端頁面上實現表單提交檔案上傳功能

shandow_發表於2020-12-23

提示:新手剛剛初學java,希望和大家多多交流


前言

在頁面上實現檔案的上傳功能


一、檔案上傳的三要素是什麼?

檔案上傳的三要素:
1.表單post請求
2.input框的type=file
3.在form表單中新增enctype=“multipart/form-data”

二、具體使用步驟

1.前端頁面程式碼

程式碼如下(示例):

<form action="/" method="post"
						class="form-horizontal" id="saveForm"
						enctype="multipart/form-data">							
						<div class="form-group row">
							<label for="title" class="control-label col-md-2">圖片上傳</label>
							<div class="col-md-10">
								<input class="form-group" name="photo" type="file" />
							</div>
						</div>
						<div class="form-group row">
							<label for="title" class="control-label col-md-2">視訊上傳</label>
							<div class="col-md-10">
								<input class="form-group" name="media" type="file" />
							</div>
						</div>										
					</form>

input框中的type屬性等於file
form表單必須是post請求
form表單必須新增enctype=“multipart/form-data”

2.後臺程式碼接收

程式碼如下(示例):

@RequestMapping("/")
	@ResponseBody
	public AjaxResult save(Vedio vedio, HttpServletRequest request, MultipartFile photo,MultipartFile media) {
		// System.out.println(article);
		System.out.println(vedio);
		try {
			service.save(vedio, request, photo,media);
			return new AjaxResult();
		} catch (Exception e) {
			// TODO: handle exception

			e.printStackTrace();
			return new AjaxResult(false, "操作失敗");
		}

	}

這裡需要注意的是,這裡方法引數必須使用MultipartFile型別 引數名必須和前端頁面中input框的name屬性值一致

3.在springMVC的配置檔案中新增檔案上傳解析器

<!-- 檔案上傳配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!--

    defaultEncoding:請求的編碼格式必須和使用者JSP的編碼一致,以便正確讀取表單中的內容。
    uploadTempDir:檔案上傳過程中的臨時目錄,上傳完成後,臨時檔案會自動刪除
    maxUploadSize:設定檔案上傳大小上限(單位為位元組)-1為無限制

  -->
  <property name="defaultEncoding" value="UTF-8" />
  <property name="maxUploadSize" value="102400000" />
  <!-- uploadTempDir可以不做設定,有預設的路徑,上傳完畢會臨時檔案會自動被清理掉 -->
  <property name="uploadTempDir" value="/upload/"></property>
</bean>

4.在服務層實現對檔案的上傳功能的封裝

public static void gofile(HttpServletRequest request,MultipartFile mFile,Vedio vedio,String p){
         // 獲取檔案存放的絕對路徑
		String path = request.getServletContext().getRealPath(p);
		if (mFile!=null) {			
			
			// System.out.println(path);
			// 判斷該資料夾是否存在
			File file = new File(path);
			if (!file.exists()) {
				//建立資料夾
				file.mkdir();
			}
			// 獲取需要上傳檔案的檔名
			String originalFilename = mFile.getOriginalFilename();
			// System.out.println(originalFilename);
			// 只需要擷取改檔名的字尾
			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
			// System.out.println(suffix);
			// 生產新的檔名字
			long currentTimeMillis = System.currentTimeMillis();
			String fileName = currentTimeMillis + "" + suffix;
			// 建立輸入輸出流
			InputStream in = null;
			try {
				in = mFile.getInputStream();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(new File(path, fileName));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 檔案拷貝
			try {
				IOUtils.copy(in, out);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 關流
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

總結

注意:

本文僅僅簡單介紹了檔案的上傳功能在SSM框架中的使用,使用檔案上傳下載功能需要在SpringMVC配置檔案中配置檔案上傳解析器
在前端表單中需要post請求 ,新增enctype="multipart/form-data"屬性
在後端使用MultipartFile 型別 引數名必須和前端中的input中的name屬性值一致。

最後,希望有幫助到你!願你學習愉快!

相關文章