問題
當上傳文件時,表單需設置 enctype="multipart/form-data",即:
<form action="UpLoadServlet" method="post" enctype="multipart/form-data">
……
</form>
這時如果表單中除了文件,還有其他類型的內容時,Servlet中用request是獲取不到值的。
解決
關於表單中只有文件上傳內容的部分見菜鳥教程,這裏不多做贅述。
這裏僅列出主體部分代碼:
picAdd.jsp
<form action="UpLoadServlet" method="post" enctype="multipart/form-data">
<div class="row form-group">
<div class="col col-md-2"><label for="text-input" class=" form-control-label">網頁鏈接:</label></div>
<div class="col-12 col-md-10"><input type="text" name="blogLink" class="form-control"></div>
</div>
<div class="row form-group">
<div class="col col-md-2"><label for="text-input" class=" form-control-label">圖片:</label></div>
<div class="col-12 col-md-10"><input type="file" name="picLink" ></div>
</div>
<div class="row form-group">
<div class="col col-md-2"><label for="text-input" class=" form-control-label">主頁顯示的文本:</label></div>
<div class="col-12 col-md-10"><input type="text" name="viewText" class="form-control"></div>
</div>
<div class="row form-group">
<div class="col col-md-2"><label for="text-input" class=" form-control-label">圖片加載失敗時顯示的內容:</label></div>
<div class="col-12 col-md-10"><input type="text" name="failText" class="form-control"> </div>
</div>
<div class="form-group text-right">
<button type="submit" class="btn btn-primary btn-md">
<i class="fa fa-dot-circle-o"></i> 保存
</button>
</div>
</form>
UpLoadServlet.java
package com.laku.fec.controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.session.SqlSession;
import com.laku.fec.model.entity.Blog;
import com.laku.fec.model.service.IPersonService;
import com.laku.mybatis.MybatisUtils;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/UploadServlet")
public class UpLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上傳文件存儲目錄
private static final String UPLOAD_DIRECTORY = "upload";
// 上傳配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
/**
* 上傳數據及保存文件
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//文件上傳**************************
// 檢測是否爲多媒體上傳
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是則停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上傳參數
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設置內存臨界值 - 超過後將產生臨時文件並存儲於臨時目錄中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 設置臨時存儲目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 設置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設置最大請求值 (包含文件和表單數據)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文處理
upload.setHeaderEncoding("UTF-8");
// 構造臨時路徑來存儲上傳的文件
// 這個路徑相對當前應用的目錄
String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
System.out.println("1:"+getServletContext().getRealPath("/"));
System.out.println("2:"+File.separator);
System.out.println("uploadPath:"+uploadPath);
// 如果目錄不存在則創建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
//表單的其他參數
String blogLink="";//1
String filePath="";//2
String viewText="";//3
String failText="";//4
try {
// 解析請求的內容提取文件數據
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單數據
int cnt = 0;
for (FileItem item : formItems) {
cnt++;
// 處理不在表單中的字段(處理文件)
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制檯輸出文件的上傳路徑
System.out.println("filePath:"+filePath);
// 保存文件到硬盤
item.write(storeFile);
request.setAttribute("message",
"文件上傳成功!");
}else{//處理表單中的非文件
//獲取value值
if(cnt==1) blogLink=item.getString("UTF-8");
else if(cnt==3) viewText=item.getString("UTF-8");
else if(cnt==4) failText=item.getString("UTF-8");
System.out.println("blogLink:"+blogLink);
System.out.println("viewText:"+viewText);
System.out.println("failText:"+failText);
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"錯誤信息: " + ex.getMessage());
}
//其餘表單內容處理**************************
SqlSession sqlSession = MybatisUtils.getSqlSession();
IPersonService service = sqlSession.getMapper(IPersonService.class);
//中文編碼
response.setContentType("text/html;charset=gb2312");
//封裝和提交
Blog b = new Blog(blogLink, filePath, viewText, failText);
int i = service.addPic(b);
sqlSession.commit();
// 跳轉
if(i>0){
response.getWriter().println("<script> type='text/javascript'>window.alert('輪播圖添加成功!');window.location.href='BackServlet?method=findBlog';</script>");
}else{
response.getWriter().println("<script> type='text/javascript'>window.alert('添加失敗!');window.location.href='backStage/picAdd.jsp';</script>");
}
}
}
其中第86-90,113-121行爲非文件表單處理的部分。