A. 怎樣使用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
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>MyJSP'index.jsp'startingpage</title>
</head>
<body>
<!--encType默認是application/x-www-form-urlencoded-->
<formaction="${pageContext.request.contextPath}/upload1"
method="POST"enctype="multipart/form-data">
<inputtype="text"name="content"><br>
<inputtype="file"name="f"><br><inputtype="submit"
value="上傳">
</form>
</body>
</html>
新建Upload1Servlet 路徑:/upload1
[java]view plain
packagecn.itcast.web.servlet;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//System.out.println("upload1servlet......");
//通過request獲取一個位元組輸入流,將所有的請求正文信息讀取到,列印到控制台
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=-1;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}
is.close();
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
}
在瀏覽器端訪問信息如下:
文件上傳概述
實現web開發中的文件上傳功能,需要完成如下二步操作:
在web頁面中添加上傳輸入項。
在Servlet中讀取上傳文件的數據,並保存在伺服器硬碟中。
如何在web頁面中添加上傳輸入項?
<input type="file">標簽用於在web頁面中添加文件上傳輸入項,設置文件上傳輸入項時注意:
1、必須設置input輸入項的name屬性,否則瀏覽器將不會發送上傳文件的數據。
2、必須把form的encType屬性設為multipart/form-data 設置該值後,瀏覽器在上傳文件時,並把文件數據附帶在http請求消息體內,並使用MIME協議對上傳的文件進行描述,以方便接收方對上傳數據進行解析和處理。
3、表單的提交方式要設置為post。
如何在Servlet中讀取文件上傳數據,並保存到本地硬碟中?
Request對象提供了一個getInputStream方法,通過這個方法可以讀取到客戶端提交過來的數據。但由於用戶可能會同時上傳多個文件,在servlet端編程直接讀取上傳數據,並分別解析出相應的文件數據是一項非常麻煩的工作,示例。
為方便用戶處理文件上傳數據,Apache 開源組織提供了一個用來處理表單文件上傳的一個開源組件( Commons-fileupload ),該組件性能優異,並且其API使用極其簡單,可以讓開發人員輕松實現web文件上傳功能,因此在web開發中實現文件上傳功能,通常使用Commons-fileupload組件實現。
使用Commons-fileupload組件實現文件上傳,需要導入該組件相應支撐jar包:Commons-fileupload和commons-io。commo-io不屬於文件上傳組件的開發jar文件,但Commons-fileupload組件從1.1版本開始,它工作時需要commons-io包的支持。
B. java高並發文件上傳下載設計問題
說實話 從軟體復或代碼角度 沒轍制 都是長連接 逃不掉的
只能從系統設計上去考慮,大致上會有以下這兩種思路(基本上是都用的):
1、對於所有的上傳的文件,根據隨機生成的名稱或code取hash用策略取模,分伺服器存/取文件,保證不觸及io瓶頸,內部文件同步策略自己考慮
2、對所有請求,分pop點分發,根據用戶的物理地址選擇相應較近的pop點處理請求(當前pop請求已滿則順延至下一pop點,依次類推)
C. JAVA 上傳下載文件
Java代碼實現文件上傳
FormFilefile=manform.getFile();
StringnewfileName=null;
Stringnewpathname=null;
StringfileAddre="/numUp";
try{
InputStreamstream=file.getInputStream();//把文件讀入
StringfilePath=request.getRealPath(fileAddre);//取系統當前路徑
Filefile1=newFile(filePath);//添加了自動創建目錄的功能
((File)file1).mkdir();
newfileName=System.currentTimeMillis()
+file.getFileName().substring(
file.getFileName().lastIndexOf('.'));
ByteArrayOutputStreambaos=newByteArrayOutputStream();
OutputStreambos=newFileOutputStream(filePath+"/"
+newfileName);
newpathname=filePath+"/"+newfileName;
System.out.println(newpathname);
//建立一個上傳文件的輸出流
System.out.println(filePath+"/"+file.getFileName());
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=stream.read(buffer,0,8192))!=-1){
bos.write(buffer,0,bytesRead);//將文件寫入伺服器
}
bos.close();
stream.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
D. java 項目開發 實現上傳視頻。
上傳視頻?只是上傳的話,相當於,上傳文件了
html如下
<form action="MultipartTestServlet" enctype="multipart/form-data" method="post">
<input type="text" name="username" /><br />
<input type="file" name="myfile" /><br/>
<input type="submit" />
</form>
java如下
MultipartTestServlet.java
package com.bug.servlet;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
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.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
public class MultipartTestServlet extends HttpServlet {
public MultipartTestServlet() {
super();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gbk");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File("c:/tmp/"));
ServletFileUpload upload = new ServletFileUpload(factory);
//upload.setHeaderEncoding("gbk");
upload.setSizeMax(2000000);
List items = new ArrayList();
try {
items = upload.parseRequest(request);
} catch (FileUploadException e1) {
System.out.println("文件上傳發生錯誤" + e1.getMessage());
}
Iterator it = items.iterator();
while(it.hasNext()){
FileItem fileItem = (FileItem) it.next();
if(fileItem.isFormField()){
System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk"));
}else{
System.out.println(fileItem.getFieldName() + " " +
fileItem.getName() + " " +
fileItem.isInMemory() + " " +
fileItem.getContentType() + " " +
fileItem.getSize());
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
File newFile = new File("c:/temp/" + fullFile.getName());
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("文件沒有選擇 或 文件內容為空");
}
}
}
}
}
}
web.xml中加入
<servlet>
<servlet-name>MultipartTestServlet</servlet-name>
<servlet-class>com.bug.servlet.MultipartTestServlet</servlet-class>
</servlet>
需要的包到這三個地方下載
http://jakarta.apache.org/commons/fileupload/下載
http://jakarta.apache.org/commons/io/下載
在http://www.servlets.com/cos/下載
關於視頻的播放,你只能自己再去找了
E. java視頻文件上傳,截取圖未保存成功,求解!!!
使用ffmpeg,下載ffmpeg相關組件到電腦中,然後用java調用命令的方式(RunTime.exec相關方法),使用ffmpeg的功能。
F. Java 批量大文件上傳下載如何實現
解決這種大文件上傳不太可能用web上傳的方式,只有自己開發插件或是當門客戶端上傳,或者用現有的ftp等。
1)開發一個web插件。用於上傳文件。
2)開發一個FTP工具,不用web上傳。
3)用現有的FTP工具。
下面是幾款不錯的插件,你可以試試:
1)Jquery的uploadify插件。具體使用。你可以看幫助文檔。
G. java怎麼實現視頻上傳
方法/步驟
1
首先這里jsp頁面的代碼 定義布局文件html的 如圖所示
H. JAVA action中如何 上傳 下載文件
/**
上傳文件
*/
public class FileAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
FileForm fileform = (FileForm) form;
//取得請求的文件集合
Hashtable hash = fileform.getMultipartRequestHandler().getFileElements();
//得到hashtable的枚舉值
Enumeration enu = hash.elements();
//如果該枚舉值包含有其它的文件
while(enu.hasMoreElements()) {
//得到文件
FormFile file = (FormFile) enu.nextElement();
System.out.println(file);
add(file);
}
return mapping.findForward("yes");
} catch (Exception e) {
e.printStackTrace();
}
return super.execute(mapping, form, request, response);
}
public void add(FormFile file){
try {
//取得寫文件的目錄
String url=servlet.getServletContext().getRealPath("upload");
File f1=new File(url);
if(!f1.exists()){//如果文件目錄不存在
f1.mkdirs();//創建目錄
}
String fileName=file.getFileName();
//創建一個文件輸入流
InputStream is=file.getInputStream();
OutputStream out=new FileOutputStream(url+"/"+fileName);
int byteRead=0;
byte[] by=new byte[8192];
while((byteRead=is.read(by, 0, 8192))!=-1){
out.write(by, 0, byteRead);
}
out.close();
is.close();
file.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
下載文件
*/
頁面一開始進去action,action負責把file文件夾下的所有文件讀入一個ArrayList中
Action代碼如下:
ArrayList list = new ArrayList();
String path=request.getRealPath("/")+"file";
String FullPath;
//System.out.println(path);
myDir=new File(path);
list.clear();
contents=myDir.listFiles();
for(int i=0;i<contents.length;i++){
FullPath=contents.getName();
list.add(FullPath);
//System.out.println(FullPath);
}
request.setAttribute("list",list);
ActionForward forward=new ActionForward("/download.jsp");
return forward;
然後進入download.jsp中,這個頁面主要負責把所有文件顯示,並提供下載連接,代碼如下:
<%@ page language="java" contentType="text/html;charset=GBK" import="java.util.ArrayList"%>
<head>
</style>
</head>
<body>
<%ArrayList list=(ArrayList)request.getAttribute("list");
for(int i=0;i<list.size();i++)
{
String a=java.net.URLEncoder.encode((String)list.get(i));
out.print("<a href=./loaded.do?name="+a+">"+list.get(i)+"</a><br>");
}
%>
</body>
</html>
注意,下劃線畫中的代碼的作用,就是解決問題的所在。
接下來可以直接傳入到loadedaction中,也可以通過一個form,我演示的是通過一個form
Form代碼如下
package org.aeolus.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public class LoadForm extends ActionForm {
/*
*Generated Methods
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接下來就是action的代碼
LoadForm doc=(LoadForm)form;
String docName = new String(doc.getName().getBytes("8859_1"));
File f;
if(docName!=""){
String docFullPath=request.getRealPath("/");
f = new File(docFullPath+"file\\"+docName);
response.reset();
response.setContentType("application/x-msdownload;charset=GBK");
System.out.print(response.getContentType());
response.setCharacterEncoding("UTF-8");
docName=java.net.URLEncoder.encode(docName,"UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" +new String(docName.getBytes("UTF-8"),"GBK"));
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) >0)
out.write(buf,0,len);
out.close();
response.wait();
ActionForward forward=new ActionForward("/download.jsp");
return forward; }
return null;
注意,下劃線畫中的代碼的作用,就是解決問題的所在。說明一下:
response.setCharacterEncoding("UTF-8");
docName=java.net.URLEncoder.encode(docName,"UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" +new String(docName.getBytes("UTF-8"),"GBK"));
如果不這樣做你將要下載的文件名是亂碼。
I. java實現文件的上傳和下載
用輸出流 接受 一個下載地址的網路流
然後將這個輸出流 保存到本地一個文件 後綴與下載地址的後綴相同··
上傳的話 將某個文件流 轉成位元組流 上傳到某個webservice方法里
-------要代碼來代碼
URL url=new URL("http://www..com/1.rar");
URLConnection uc=url.openConnection();
InputStream in=uc.getInputStream();
BufferedInputStream bis=new BufferedInputStream(in);
FileOutputStream ft=new FileOutputStream("E://1.rar");
這是下載 上傳太麻煩就不給寫了
J. java如何實現文件上傳和下載的功能
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.*;
import net.sf.json.JSONObject;
import action.StudentAction;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean result=true;
SmartUpload mySmartUpload=new SmartUpload();
mySmartUpload.initialize(this.getServletConfig(), request,response);
mySmartUpload.setTotalMaxFileSize(50*1024*1024);//大小限制
mySmartUpload.setAllowedFilesList("doc,docx");//後綴名限制
try {
mySmartUpload.upload();
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
myFile.saveAs("/file/"+1+".doc");//保存目錄
} catch (SmartUploadException e) {
e.printStackTrace();result=false;
}
//*****************************//
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
out.close();
}
}
//我這是ajax方式的,不想這樣,把//**********************//以下部分修改就行了
//需要SmartUpload組件,去網上下個就行了,也有介紹的