JavaWeb上傳下載下傳案例
- *
2種方式的上傳下載下傳檔案案例,要導入jsmartcom_zh_CN
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9kFVPdXRU5keBRkTmZEWjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DOzgTMwYTN4ADOwEDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
目錄清單
定義清單
- Markdown Extra 定義清單文法: 項目1 項目2
- 定義 A
- 定義 B 項目3
- 定義 C
- 定義 D
定義D内容
代碼塊
批量下載下傳BatchDownloadServlet
package com.demo.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BatchDownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/x-msdownload");
resp.setHeader("Content-Disposition", "attachment;filename=test.zip");
String path = getServletContext().getRealPath("/") + "images/";
String[] filenames = req.getParameterValues("filename");
String str = "";
String rt = "\r\n";
ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
for(String filename : filenames){
str += filename + rt;
File file = new File(path + filename);
zos.putNextEntry(new ZipEntry(filename));
FileInputStream fis = new FileInputStream(file);
byte b[] = new byte[];
int n = ;
while((n = fis.read(b)) != -){
zos.write(b, , n);
}
zos.flush();
fis.close();
}
zos.setComment("download success:" + rt + str);
zos.flush();
zos.close();
}
}
檔案下載下傳DownloadServlet
package com.demo.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//擷取檔案下載下傳路徑
String path = getServletContext().getRealPath("/") + "images/";
String filename = req.getParameter("filename");
File file = new File(path + filename);
if(file.exists()){
//設定相應類型application/octet-stream
resp.setContentType("application/x-msdownload");
//設定頭資訊
resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
InputStream inputStream = new FileInputStream(file);
ServletOutputStream ouputStream = resp.getOutputStream();
byte b[] = new byte[];
int n ;
while((n = inputStream.read(b)) != -){
ouputStream.write(b,,n);
}
//關閉流、釋放資源
ouputStream.close();
inputStream.close();
}else{
req.setAttribute("errorResult", "檔案不存在下載下傳失敗!");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
dispatcher.forward(req, resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}
簡易下載下傳
package com.demo.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class SmartDownloadServlet 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 {
String filename = request.getParameter("filename");
SmartUpload su = new SmartUpload();
su.initialize(getServletConfig(), request, response);
su.setContentDisposition(null);
try {
su.downloadFile("/images/"+ filename);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
package com.demo.servlet;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
public class SmartUploadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設定上傳檔案儲存路徑
String filePath = getServletContext().getRealPath("/") + "images";
File file = new File(filePath);
if(!file.exists()){
file.mkdir();
}
SmartUpload su = new SmartUpload();
//初始化對象
su.initialize(getServletConfig(), req, resp);
//設定上傳檔案大小
su.setMaxFileSize(**);
//設定所有檔案的大小
su.setTotalMaxFileSize(**);
//設定允許上傳檔案類型
su.setAllowedFilesList("txt,jpg,gif");
String result = "上傳成功!";
try {
//設定禁止上傳的檔案類型
su.setDeniedFilesList("rar,jsp,js");
//上傳檔案
su.upload();
int count = su.save(filePath);
System.out.println("上傳成功" + count + "個檔案!");
} catch (Exception e) {
result = "上傳失敗!";
e.printStackTrace();
}
for(int i =; i < su.getFiles().getCount(); i++){
com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
System.out.println("---------------------------");
System.out.println("表單當中name屬性值:" + tempFile.getFieldName());
System.out.println("上傳檔案名:" + tempFile.getFieldName());
System.out.println("上傳檔案長度:" + tempFile.getSize());
System.out.println("上傳檔案的拓展名:" + tempFile.getFileExt());
System.out.println("上傳檔案的全名:" + tempFile.getFilePathName());
System.out.println("---------------------------");
}
req.setAttribute("result", result);
req.getRequestDispatcher("jsp/02.jsp").forward(req, resp);
}
}
上傳檔案
package com.demo.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//從request當中擷取流資訊
InputStream fileSource = req.getInputStream();
String tempFileName = "E:/tempFile";
//tempFile指向臨時檔案
File tempFile = new File(tempFileName);
//outputStram檔案輸出流指向這個臨時檔案
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte b[] = new byte[];
int n;
while(( n = fileSource.read(b)) != -){
outputStream.write(b, , n);
}
//關閉輸出流、輸入流
outputStream.close();
fileSource.close();
//擷取上傳檔案的名稱
RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
randomFile.readLine();
String str = randomFile.readLine();
int beginIndex = str.lastIndexOf("\\") + ;
int endIndex = str.lastIndexOf("\"");
String filename = str.substring(beginIndex, endIndex);
System.out.println("filename:" + filename);
//重新定位檔案指針到檔案頭
randomFile.seek();
long startPosition = ;
int i = ;
//擷取檔案内容 開始位置
while(( n = randomFile.readByte()) != - && i <=){
if(n == '\n'){
startPosition = randomFile.getFilePointer();
i ++;
}
}
startPosition = randomFile.getFilePointer() -;
//擷取檔案内容 結束位置
randomFile.seek(randomFile.length());
long endPosition = randomFile.getFilePointer();
int j = ;
while(endPosition >= && j<=){
endPosition--;
randomFile.seek(endPosition);
if(randomFile.readByte() == '\n'){
j++;
}
}
endPosition = endPosition -;
//設定儲存上傳檔案的路徑
String realPath = getServletContext().getRealPath("/") + "images";
File fileupload = new File(realPath);
if(!fileupload.exists()){
fileupload.mkdir();
}
File saveFile = new File(realPath,filename);
RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
//從臨時檔案當中讀取檔案内容(根據起止位置擷取)
randomFile.seek(startPosition);
while(startPosition < endPosition){
randomAccessFile.write(randomFile.readByte());
startPosition = randomFile.getFilePointer();
}
//關閉輸入輸出流、删除臨時檔案
randomAccessFile.close();
randomFile.close();
tempFile.delete();
req.setAttribute("result", "上傳成功!");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
dispatcher.forward(req, resp);
}
}
生成目錄:
- JavaWeb上傳下載下傳案例
-
- 定義清單
- 代碼塊
-