Jsp+Servlet實現的檔案上傳

來源:互聯網
上載者:User

檔案上傳需要用到cos.jar包。檔案上傳的顯示頁面index.jsp檔案如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>File upload</title></head><body><center><form name="upform" action="UploadServlet" method="POST" enctype="multipart/form-data"><input type="file" name="file" id="file" /><input type="submit" value="提交" /></form></center></body></html>

表單必須使用post方式提交,enctype=“multipart/form-data”這句話是必須要寫的。對應的UploadServlet.java檔案如下:

import java.io.File;import java.io.IOException;import java.util.Enumeration;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hh.excel.ExcelData;import com.oreilly.servlet.MultipartRequest;public class UploadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 上傳檔案// 檔案上傳後,儲存在C盤根目錄下request.setCharacterEncoding("utf-8");String saveDirectory = new File("c:/").getAbsolutePath();String filePath = "";// 每個檔案最大500mint maxPostSize = 1 * 500 * 1024 * 1024;// response的編碼為"utf-8",同時採用預設的檔案名稱衝突解決方案策略,實現上傳MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "utf-8");// 輸出反饋資訊Enumeration files = multi.getFileNames();while (files.hasMoreElements()) {String name = (String) files.nextElement();File f = multi.getFile(name);if (f != null) {String fileName = multi.getFilesystemName(name);filePath = saveDirectory + "\\" + fileName;System.out.println(filePath);}}}}

相關文章

聯繫我們

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