package com.jege.spring.mvc;
import java.io.File;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Controller
public class CommonsMultipartResolverUploadController{
// http://localhost:8080/upload
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String uploadGet() {
System.out.println("先以get的請求方式顯示上傳頁面");
return "upload";
}
int i = 0;// 簡單改變上傳文件的名字
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadPost(HttpServletRequest request) throws Exception {
System.out.println("在以post請求方式處理上傳的請求");
// 記錄開始上傳文件的時間
long startTime = System.currentTimeMillis();
String webapp = request.getServletContext().getRealPath("/upload");
System.out.println("上傳文件保存到服務器webapp的路徑:" + webapp);
// 存放文件的路徑
File deskFile = new File(webapp, "eclipse.zip");
System.out.println("上傳文件存放的最終路徑:" + deskFile.getAbsolutePath());
// 將當前上下文初始化給 CommonsMutipartResolver:配置上傳文件解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 檢查form中是否有enctype="multipart/form-data",便是是否有文件上傳
if (multipartResolver.isMultipart(request)) {
// 將request變成多部件MultipartHttpServletRequest
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 獲取multiRequest 中全部的文件名
Iterator<String> iter = multiRequest.getFileNames();
// 遍歷全部文件
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {// 處理上傳
file.transferTo(deskFile);
}
}
}
// 添加提示信息
request.setAttribute("msg", "上傳成功");
// 記錄結束上傳文件的時間
long endTime = System.currentTimeMillis();
System.out.println("上傳究竟用了多少時間:" + String.valueOf(endTime - startTime) + "ms");
// 直接轉發到upload.jsp
return "upload";
}
}
https://github.com/je-ge/springjava
若是以爲個人文章或者代碼對您有幫助,能夠請我喝杯咖啡。您的支持將鼓勵我繼續創做!謝謝!
git