jsp+servlet實現多個檔案的上傳__js

來源:互聯網
上載者:User
jsp代碼<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%><fmt:setBundle basename="csdn" /><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'Uplode.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!-- 引入jquery easyui的css樣式 --><link rel="stylesheet" type="text/css"href="${pageContext.request.contextPath}/themes/default/easyui.css"><link rel="stylesheet" type="text/css"href="${pageContext.request.contextPath}/themes/icon.css"><!-- 引入jQuery easyui的js檔案 並且引入了jquery.js檔案 --><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.easyui.min.js"></script><script type="text/javascript">$(function() {/* 註冊添加按鈕的點擊事件 */$("#addFile").click(addFile);});var addFile = function() {var $file = $("<input type='file' name='UplodeName'/>");$("#fileUplodeDiv").append($file).append($("<br>"));};</script></head><body><form action="${pageContext.request.contextPath }/uplodes.action"enctype="multipart/form-data" method="post">上傳者:<input type="text" name="name"> <br> 上檔案:<inputtype="file" name="UplodeName" value="你好"><div id="fileUplodeDiv"></div><br> <br> <input type="submit" value="提交檔案"> <input type="button"value="添加檔案" id="addFile" > </form></body></html>





java代碼,web.xml中註冊的是/uplodes.actionpackage servlet;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.List;import javax.servlet.ServletException;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.FileUploadException;import org.apache.commons.fileupload.UploadContext;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class UplodesServlet extends HttpServlet {private int maxFileSize = 1024 * 1024 * 10;// 定義檔案的路徑private String path = "D:\\";private String fileType = "";public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 解決檔案的中文亂碼request.setCharacterEncoding("UTF-8");// 建立磁碟檔案工廠處理對象DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();// 建立伺服器檔案上傳處理對象ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);/* * // 設定檔案最大的上傳的大小 servletFileUpload.setFileSizeMax(maxFileSize);// 10M */try {// 解析request請求中的欄位和請求的內容List<FileItem> fileItems = servletFileUpload.parseRequest(request);// 遍曆解析出的list集合for (FileItem fileItem : fileItems) {// 判斷解析出的是否是普通的文字欄位if (fileItem.isFormField()) {// 擷取欄位名稱String filedName = fileItem.getName();// 擷取欄位名對應的值String filedValue = fileItem.getString("UTF-8");// 輸出文字框的內容System.out.println(filedName + "=================="+ filedValue);} else {// 判斷資源檔大小是否合法if (fileItem.getSize() <= maxFileSize) {// 擷取欄位名String fileName = fileItem.getName();// 解決不同瀏覽器的檔案路徑問題// ie或是其它的是這樣的路徑C:\Users\chenhongjun\Desktop\tag_1388040641790.txt// Firefox的只有檔案名稱// D:\視頻\day52\錄影12.aviif (!fileName.equals("")) {// 擷取上傳檔案的類型System.out.println(fileItem.getContentType());// 判斷是否是指定的類型檔案if (fileItem.getContentType().equals("image/jpeg")) {// 判斷是否包含"\"int index = fileName.lastIndexOf("\\");if (index != -1) {fileName = fileName.substring(index + 1);}// 指定檔案儲存體的路徑File file = new File(path,newFileName(fileName));// 建立輸出資料流FileOutputStream fos = new FileOutputStream(file);// 擷取request中解析出的輸入資料流InputStream is = fileItem.getInputStream();// 建立緩衝區域byte[] buffer = new byte[1024];int len = 0;while ((len = (is.read(buffer))) != -1) {// 將緩衝區內的內容寫出fos.write(buffer, 0, len);}fos.flush();fos.close();is.close();// 刪除臨時檔案fileItem.delete();System.out.println("success");} else {System.out.println("請上傳指定的檔案類型");}} else {System.out.println("請選擇要上傳的檔案");}} else {System.out.println("檔案過大,超出" + maxFileSize);}}}} catch (FileUploadException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}// 檔案名稱的處理public String newFileName(String oldFileName) {// 擷取最後一個"."出現的位置下標int index = oldFileName.lastIndexOf(".");// 截取最後一個"."之前的內容String frontStr = oldFileName.substring(0, index);// 擷取最後一個"."之後的內容String behindStr = oldFileName.substring(index);// 重新拼接檔案的名稱String newFileName = frontStr + System.currentTimeMillis() + "_"+ behindStr;return newFileName;}}



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.