jsp檔案上傳與下載執行個體代碼

來源:互聯網
上載者:User

檔案上傳複製代碼 代碼如下:public class UploadServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
SmartUpload myupload = new SmartUpload();
ServletConfig config = getServletConfig();
myupload.initialize(config,req,resp);
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
out.println("<h2>處理上傳的檔案</h2>");
out.println("<hr>");

try {
myupload.setMaxFileSize(1024*1024);
myupload.setTotalMaxFileSize(5*1024*1024);

myupload.setAllowedFilesList("doc,txt,jpg,gif");
myupload.setDeniedFilesList("exe,bat,jsp,htm,html");
myupload.upload();//上傳檔案,此項是必須的
int count = myupload.getFiles().getCount();
Request myRequest = myupload.getRequest();
String rndFilename,fileExtName,fileName,filePathName;
Date dt = null;
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
//一一提取上傳檔案資訊,同時可保持檔案
for(int i = 0; i < count; i++){
File file = myupload.getFiles().getFile(i);
if(file.isMissing())
continue;
fileName = new String(file.getFileName().getBytes(),"utf-8");//擷取檔案名稱
filePathName = new String(file.getFilePathName().getBytes(),"utf-8");
fileExtName = file.getFileExt();
dt = new Date(System.currentTimeMillis());
Thread.sleep(100);
rndFilename = fmt.format(dt)+i+"."+fileExtName;
out.println("第"+(i+1)+"個檔案的檔案資訊:<br>");
out.println(" 檔案名稱為:"+fileName+"<br>");
out.println(" 副檔名為:"+fileExtName+"<br>");
out.println(" 檔案全名:"+filePathName+"<br>");
out.println(" 檔案大小:"+file.getSize()/1024+"kb<br>");
//建立檔案儲存位置
ServletContext context = req.getServletContext();
String savePath = context.getRealPath("/upload/");
java.io.File folder = new java.io.File(savePath);
if(!folder.exists()){
folder.mkdirs();
}
out.println(" 檔案儲存路徑:"+savePath);
file.saveAs(savePath+"/"+rndFilename,SmartUpload.SAVE_PHYSICAL);
}

} catch (Exception e) {
out.println("檔案上傳失敗!!!!");
e.printStackTrace();
}
out.flush();
out.close();

}
}

複製代碼 代碼如下:<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.jspsmart.upload.*" %>
<%
//設定請求編碼方式,否則遇到中文就會亂碼
request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上傳檔案執行個體</title>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
$("#number").change(function(){
var number = $("#number").attr("value");
$("#files").html("");
for(var i = 0; i < number; i++){
$("#files").append("<input type='file' name='file''"+i+"'><br/>");
}
});
});
</script>
</head>
<body>
<h2>上傳檔案執行個體</h2>
請選擇上傳檔案數量:
<select id="number">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<div id="files"></div>
<input type="submit" value="提交"/>
</form>
</body>
</html>

檔案下載複製代碼 代碼如下:<%
response.setContentType("application/x-download");//設定為下載application/x-download
String filedownload = "/要下載的檔案名稱";//即將下載的檔案的相對路徑
String filedisplay = "最終要顯示給使用者的儲存檔案名稱";//下載檔案時顯示的檔案儲存名稱
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
try
{
RequestDispatcher dis = application.getRequestDispatcher(filedownload);
if(dis!= null)
{
dis.forward(request,response);
}
response.flushBuffer();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
}
%>

相關文章

聯繫我們

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