锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
聽聽聽聽聽聽jsp鏂囦歡涓婁紶涓昏浣跨敤浜嗕袱涓猨ar鍖咃紝commons-fileupload-1.2.1.jar鍜宑ommons-io-1.4.jar
2.浠g爜瀹炵幇
聽聽聽聽 public class UploadServlet extends HttpServlet {
聽/**
聽 *
聽 */
聽private static final long serialVersionUID = 1L;
聽private ServletContext sc;
聽private String savePath;
聽@Override
聽protected void doGet(HttpServletRequest request,
聽聽聽HttpServletResponse response) throws ServletException, IOException {
聽聽doPost(request, response);
聽}
聽@Override
聽protected void doPost(HttpServletRequest request,
聽聽聽HttpServletResponse response) throws ServletException, IOException {
聽聽System.out.println("璇鋒眰榪涙潵浜?.........");
聽聽// 璁劇疆璇鋒眰鐨勭紪鐮?br />聽聽request.setCharacterEncoding("UTF-8");
聽聽DiskFileItemFactory factory = new DiskFileItemFactory();//鍒涘緩涓涓鐩樻枃浠跺伐鍘?br />聽聽ServletFileUpload upload = new ServletFileUpload(factory);
聽聽try {
聽聽聽List items = upload.parseRequest(request);
聽聽聽Iterator it = items.iterator();
聽聽聽while (it.hasNext()) {
聽聽聽聽FileItem item = (FileItem) it.next();
聽聽聽聽if (item.isFormField()) {
聽聽聽聽聽System.out.println("琛ㄥ崟鐨勫弬鏁板悕縐幫細" + item.getFieldName()
聽聽聽聽聽聽聽+ ",瀵瑰簲鐨勫弬鏁板鹼細" + item.getString("UTF-8"));
聽聽聽聽} else {
聽聽聽聽聽// 鑾峰彇鏂囦歡鎵╁睍鍚?br />聽聽聽聽聽String strtype = item.getName().substring(
聽聽聽聽聽聽聽item.getName().length() - 3,
聽聽聽聽聽聽聽item.getName().length());
聽聽聽聽聽strtype = strtype.toLowerCase();
聽聽聽聽聽if (strtype == "jpg" || strtype == "gif"
聽聽聽聽聽聽聽|| strtype == "txt") {
聽聽聽聽聽聽if (item.getName() != null
聽聽聽聽聽聽聽聽&& !item.getName().equals("")) {
聽聽聽聽聽聽聽System.out.println("涓婁紶鏂囦歡鐨勫ぇ灝忥細" + item.getSize());
聽聽聽聽聽聽聽System.out.println("涓婁紶鏂囦歡鐨勭被鍨嬶細"
聽聽聽聽聽聽聽聽聽+ item.getContentType());
聽聽聽聽聽聽聽System.out.println("涓婁紶鏂囦歡鐨勫悕縐幫細" + item.getName());
聽聽聽聽聽聽聽System.out.println("鏂囦歡鐨勬墿灞曞悕" + strtype);
聽聽聽聽聽聽聽File tempFile = new File(item.getName());
聽聽聽聽聽聽聽File file = new File(
聽聽聽聽聽聽聽聽聽sc.getRealPath("/") + savePath, tempFile
聽聽聽聽聽聽聽聽聽聽聽.getName());
聽聽聽聽聽聽聽item.write(file);
聽聽聽聽聽聽聽request.setAttribute("upload.message", "涓婁紶鏂囦歡鎴愬姛錛?);
聽聽聽聽聽聽} else {
聽聽聽聽聽聽聽request.setAttribute("upload.message",
聽聽聽聽聽聽聽聽聽"娌℃湁閫夋嫨涓婁紶鏂囦歡鑾峰彇鏍煎紡涓嶆敮鎸?);
聽聽聽聽聽聽}
聽聽聽聽聽} else {
聽聽聽聽聽聽request.setAttribute("upload.message", "涓婁紶鏂囦歡鏍煎紡涓嶆敮鎸?);
聽聽聽聽聽}
聽聽聽聽}
聽聽聽}
聽聽} catch (Exception e) {
聽聽聽e.printStackTrace();
聽聽聽request.setAttribute("upload.message", "涓婁紶鏂囦歡涓嶆垚鍔燂紒");
聽聽}
聽聽// 杞彂
聽聽request.getRequestDispatcher("/uploadResult.jsp").forward(request,
聽聽聽聽response);
聽}
聽@Override
聽public void init(ServletConfig config) throws ServletException {
聽聽savePath = config.getInitParameter("savePath");
聽聽sc = config.getServletContext();
聽}