Servlet支援上傳多張圖片

來源:互聯網
上載者:User

標籤:

首先前端的表單是這個形式:

<form  target="_self" method="post" action="fileUploadMultyServlet" enctype="multipart/form-data" >

<label>上傳材料<input type="file" id="image" name=‘image‘></label>
<label>上傳材料<input type="file" id="image1" name=‘image1‘></label>
<label>上傳材料<input type="file" id="image2" name=‘image2‘></label>
<input type="submit" class="btn-u" value="提交">

</form>

然後上傳圖片的servlet代碼如下:

public class FileUploadMultyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private File uploadPath;
private File tempPath;

@Override
public void init() throws ServletException {

uploadPath = new File(getServletContext().getRealPath("upload"));
System.out.println("uploadPath=====" + uploadPath);
// 如果目錄不存在
if (!uploadPath.exists()) {
// 建立目錄
uploadPath.mkdir();
}

// 臨時目錄
// File tempFile = new File(item.getName())構造臨時對象
tempPath = new File(getServletContext().getRealPath("temp"));
if (!tempPath.exists()) {
tempPath.mkdir();
}

// 如果不顯示調用父類方法,就不會有itemManager執行個體,因此會造成null 指標
super.init();

}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

@SuppressWarnings("deprecation")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 從item_upload.jsp中拿取資料,因為上傳頁的編碼格式跟一般的不同,使用的是enctype="multipart/form-data"
// form提交採用multipart/form-data,無法採用req.getParameter()取得資料
// String itemNo = req.getParameter("itemNo");
// System.out.println("itemNo======" + itemNo);

/******************************** 使用 FileUpload 組件解析表單 ********************/
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
factory.setRepository(tempPath);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000 * 20);

try {
List<?> items = upload.parseRequest(request);
String data = "";
int i = 0;
String itemNo = "";
String fileName = "";
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
i++;
data = item.getString();
if ("itemNo".equals(item.getFieldName())) {
itemNo = item.getString();
}
}
// 是否為input="type"輸入欄位
else if (!item.isFormField()) {
// 上傳檔案的名稱和完整路徑
fileName = item.getName();
System.out.println("filename==="+fileName);
long size = item.getSize();
// 判斷是否選擇了檔案
if ((fileName == null || fileName.equals("")) && size == 0) {
continue;
}else{
fileName = System.currentTimeMillis() + ".jpg";
}
// 截取字串 如:C:\WINDOWS\Debug\PASSWD.LOG
fileName = fileName.substring(
fileName.lastIndexOf("\\") + 1, fileName.length());

// 儲存檔案在伺服器的物理磁碟中:第一個參數是:完整路徑(不包括檔案名稱)第二個參數是:檔案名稱
// item.write(file);
// 修改檔案名稱和物料名一致,且強行修改了副檔名為gif
// item.write(new File(uploadPath, itemNo + ".gif"));
// 將檔案儲存到目錄下,不修改檔案名稱
item.write(new File(uploadPath, fileName));
}
}
response.sendRedirect(request.getContextPath() + "/people_require.html");
} catch (Exception e) {
e.printStackTrace();
}

}
}

最後在你Tomcat項目路徑下的upload可以看到三張圖片,效果如下:

 

 

Servlet支援上傳多張圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.