導航:首頁 > 文件教程 > servlet大文件下載

servlet大文件下載

發布時間:2024-07-25 06:53:31

① 怎樣使用javaweb實現上傳視頻和下載功能

文件上傳就是將客戶端資源,通過網路傳遞到伺服器端。

因為文件數據比較大,必須通過文件上傳才可以完成將數據保存到資料庫端的操作。

文件上傳的本質就是IO流操作。

演示:文件上傳應該如何操作?

瀏覽器端:
1.method=post 只有post才可以攜帶大數據
2.必須使用<input type='file' name='f'>要有name屬性
3.encType="multipart/form-data"
伺服器端:
request對象是用於獲取請求信息。
它有一個方法 getInputStream(); 可以獲取一個位元組輸入流,通過這個流,可以讀取到
所有的請求正文信息.
文件上傳原理:
瀏覽器端注意上述三件事,在伺服器端通過流將數據讀取到,在對數據進行解析.
將上傳文件內容得到,保存在伺服器端,就完成了文件上傳。

注意:在實際開發中,不需要我們進行數據解析,完成文件上傳。因為我們會使用文件上傳的工具,它們已經封裝好的,提供API,只要調用它們的API就可以完成文件上傳操作.我們使用的commons-fileupload,它是apache提供的一套開源免費的文件上傳工具。

代碼演示文件上傳的原理:

在WebRoot下新建upload1.jsp

[html]view plain

② 用Java的三大框架實現文件的上傳下載,求代碼啊,最好是分為action,service,serv

package cn.itcast.struts2.demo1;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
* 完成文件上傳 (不是解析上傳內容,因為上傳內容 由fileUpload攔截器負責解析)
*
* @author seawind
*
*/
public class UploadAction extends ActionSupport {
// 接收上傳內容
// <input type="file" name="upload" />
private File upload; // 這里變數名 和 頁面表單元素 name 屬性一致
private String uploadContentType;
private String uploadFileName;

public void setUpload(File upload) {
this.upload = upload;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}

@Override
public String execute() throws Exception {
if (upload == null) { // 通過xml配置 required校驗器 完成校驗
// 沒有上傳文件
return NONE;
}
// 將上傳文件 保存到伺服器端
// 源文件 upload
// 目標文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload") + "/" + uploadFileName);
// 文件復制 使用commons-io包 提供 工具類
FileUtils.File(upload, destFile);
return NONE;
}
}
多文件上傳
package cn.itcast.struts2.demo1;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
* 支持多文件上傳
*
* @author seawind
*
*/
public class MultiUploadAction extends ActionSupport {
// 接收多文件上傳參數,提供數組接收就可以了
private File[] upload;
private String[] uploadContentType;
private String[] uploadFileName;

public void setUpload(File[] upload) {
this.upload = upload;
}

public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}

public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}

@Override
public String execute() throws Exception {
for (int i = 0; i < upload.length; i++) {
// 循環完成上傳
File srcFile = upload[i];
String filename = uploadFileName[i];

// 定義目標文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload" + "/" + filename));
FileUtils.File(srcFile, destFile);
}
return NONE;
}
}

③ 我寫了個下載程序,用Java寫的,但是寫完以後發現下載大文件的時候報錯,內存溢出,能看看是哪的問題么

不能一次讀取完,大文件很容易內存溢出。參考下:

publicstaticvoiddownload(Stringpath,HttpServletResponseresponse)throwsException{
try{
Filefile=newFile(path);
if(file.exists()){
Stringfilename=file.getName();
InputStreamfis=newBufferedInputStream(newFileInputStream(file));
response.reset();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename="+newString(filename.getBytes(),"iso-8859-1"));
response.addHeader("Content-Length",""+file.length());
OutputStreamtoClient=newBufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
byte[]buffer=newbyte[1024*1024*4];
inti=-1;
while((i=fis.read(buffer))!=-1){
toClient.write(buffer,0,i);

}
fis.close();
toClient.flush();
toClient.close();
try{
response.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}else{
PrintWriterout=response.getWriter();
out.print("<script>");
out.print("alert("notfindthefile")");
out.print("</script>");
}
}catch(IOExceptionex){
PrintWriterout=response.getWriter();
out.print("<script>");
out.print("alert("notfindthefile")");
out.print("</script>");
}

}

④ struts2的action中去訪問一個文件,下載到本地

要通過param來寫
<result type="redirectAction">
<param name="namespace">/p1</param> (這里內要寫package的容namespace)
<param name="actionName">a1</param> (這里寫action的name)
</result>

⑤ jsp 文件上傳和下載

1.jsp頁面
<s:form action="fileAction" namespace="/file" method="POST" enctype="multipart/form-data">
<!-- name為後台對應的參數名稱 -->
<s:file name="files" label="file1"></s:file>
<s:file name="files" label="file2"></s:file>
<s:file name="files" label="file3"></s:file>
<s:submit value="提交" id="submitBut"></s:submit>
</s:form>
2.Action
//單個文件上傳可以用 File files,String filesFileName,String filesContentType
//名稱要與jsp中的name相同(三個變數都要生成get,set)
private File[] files;
// 要以File[]變數名開頭
private String[] filesFileName;
// 要以File[]變數名開頭
private String[] filesContentType;

private ServletContext servletContext;

//Action調用的上傳文件方法
public String execute() {
ServletContext servletContext = ServletActionContext.getServletContext();
String dataDir = servletContext.getRealPath("磨脊塵/file/upload");
System.out.println(dataDir);
for (int i = 0; i < files.length; i++) {
File saveFile = new File(dataDir, filesFileName[i]);
files[i].renameTo(saveFile);
}
return "success";
}
3.配置上傳文件臨時文件夾(在struts.xml中配置)
<constant name="struts.multipart.saveDir" value="c:/temp"/>
文件下載
1.下載的url(到Action)
<a href="${pageContext.request.contextPath}/file/fileAction!down.action">下載</a>
2.struts.xml配置
<package name="file" namespace="野神/file" extends="struts-default">
<action name="fileAction" class="com.struts2.file.FileAction">
<!-- 下載文件配置 -->
<!--type 為 stream 應用 StreamResult 處理-->
<result name="down" type="stream">
<!--
不管實際類型,待下載文件 ContentType 統一指定為 application/octet-stream
默認為 text/plain
-->
<param name="contentType">application/octet-stream</param>
<!--
默認就是 inputStream,它將會指示 StreamResult 通過 inputName 屬性值的 getter 方法,
比如這里就是 getInputStream() 來獲取下載文件的內容,意味著瞎禪你的 Action 要有這個方法
-->
<param name="inputName">inputStream</param>
<!--
默認為 inline(在線打開),設置為 attachment 將會告訴瀏覽器下載該文件,filename 指定下載文
件保有存時的文件名,若未指定將會是以瀏覽的頁面名作為文件名,如以 download.action 作為文件名,
這里使用的是動態文件名,${fileName}, 它將通過 Action 的 getFileName() 獲得文件名
-->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 輸出時緩沖區的大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
3.Action
//Action調用的下載文件方法
public String down() {
return "down";
}

//獲得下載文件的內容,可以直接讀入一個物理文件或從資料庫中獲取內容
public InputStream getInputStream() throws Exception {
String dir = servletContext.getRealPath("/file/upload");
File file = new File(dir, "icon.png");
if (file.exists()) {
//下載文件
return new FileInputStream(file);

//和 Servlet 中不一樣,這里我們不需對輸出的中文轉碼為 ISO8859-1
//將內容(Struts2 文件下載測試)直接寫入文件,下載的文件名必須是文本(txt)類型
//return new ByteArrayInputStream("Struts2 文件下載測試".getBytes());
}
return null;
}

// 對於配置中的 ${fileName}, 獲得下載保存時的文件名
public String getFileName() {
String fileName ="圖標.png";
try {
// 中文文件名也是需要轉碼為 ISO8859-1,否則亂碼
return new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "icon.png";
}
}

⑥ resin鏈嶅姟鍣ㄤ笅鐢╦ava涓嬭澆pdf鏂囦歡錛屼笅杞戒笅鏉ョ殑鏂囦歡姣旀簮鏂囦歡澶т簡涓鍊嶅氾紝涓嶈兘鎵撳紑銆

榪欎釜浼間箮鐪熸湁闂棰橈紝鎶婂驚鐜璇誨彇鍜屽啓鍑烘槸涓嶆槸瑕佹敼鎴愯繖鏍鋒洿濂戒竴浜
while ((read = input.read(buffBytes,0,1024)) != -1) {
allLength += read;
os.write(buffBytes, 0, read);
}

⑦ jsp+servlet實現文件上傳與下載源碼

上傳:
需要導入兩個包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
* 上傳附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {

private static String path = "";

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

/*
* post處理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

path = this.getServletContext().getRealPath("/upload");

try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);

for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName();
//getName()返回的是文件名字 普通域沒有文件 返回NULL
// String Name = fileItem.getName();
String Content = fileItem.getString("gbk");
request.setAttribute(FieldName, Content);
} else {

String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1);
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute("result", "上傳文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("result", "上傳失敗,請查找原因,重新再試!");
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response);
}

}

下載(i/o流)無需導包:
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 下載文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 8594448765428224944L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

/*
* 處理請求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name = request.getParameter("fileName");

System.out.print("dddddddddd:" + name);
// web絕對路徑
String path = request.getSession().getServletContext().getRealPath("/");
String savePath = path + "upload";

// 設置為下載application/x-download
response.setContentType("application/x-download");
// 即將下載的文件在伺服器上的絕對路徑
String filenamedownload = savePath + "/" + name;
// 下載文件時顯示的文件保存名稱
String filenamedisplay = name;
// 中文編碼轉換
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
try {
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {

}

}

}

⑧ java web 如何獲得文件上傳大小

有一種叫jspsmartupload的包用來簡化文件上傳下載的編寫
裡面可以獲取文件大小

//取得文件
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
//取得文件名
String fileName = myFile.getFileName();
//取得文件大小
int fileSize = myFile.getSize();
這是基於spring架構的上傳文件支持多個文件上傳,拿到file對象後,直接file.size()就可以獲取文件的大小,
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
for (Iterator it = multipartHttpServletRequest.getFileNames(); it.hasNext();) {
String key = (String) it.next();
MultipartFile file = multipartHttpServletRequest.getFile(key);
String originalFilename = file.getOriginalFilename();
long size = file.getSize();//文件大小需要轉換成KB或M
if (StringUtils.isNotBlank(originalFilename)) {
String suffixName = originalFilename.indexOf(".") == -1 ? "" : originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
try {
InputStream inputStream = file.getInputStream();
byte[] ToByteArray = FileCopyUtils.ToByteArray(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

閱讀全文

與servlet大文件下載相關的資料

熱點內容
painter2015視頻教程 瀏覽:204
jsperror 瀏覽:183
網路到底怎麼賺錢 瀏覽:402
蘋果耳機插口接觸不良 瀏覽:934
運動手環app哪個好 瀏覽:854
java設置double精度 瀏覽:587
java代碼分享網站 瀏覽:321
ps怎麼復制到文件裡面 瀏覽:360
win7管理員指紋登錄密碼忘了怎麼辦 瀏覽:38
c是一次性插入多少條數據 瀏覽:928
u盤文件編輯軟體 瀏覽:767
vb如何打開pdf文件 瀏覽:351
soundlinkiii升級 瀏覽:64
如何把文件改成cad 瀏覽:676
如何把多個監控合在一個網路內 瀏覽:637
qq的頭像在哪個文件夾 瀏覽:468
linuxexfat補丁 瀏覽:582
excelvb編程怎麼輸出數 瀏覽:737
567位qq 瀏覽:172
qq網名女生傷感 瀏覽:292

友情鏈接