A. java怎麼實現視頻上傳
方法/步驟
B. java手機上傳視頻代碼
你好
android客戶端代碼:
public class MainActivity extends Activity
{
private TextView uploadInfo;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadInfo = (TextView) findViewById(R.id.upload_info);
uploadFile();
}
public void uploadFile()
{
//伺服器端地址
String url = "http://192.168.0.108:8080/UploadFileServer/upload";
//手機端要上傳的文件,首先要保存你手機上存在該文件
String filePath = Environment.getExternalStorageDirectory()
+ "/1/power.apk";
AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams param = new RequestParams();
try
{
param.put("file", new File(filePath));
param.put("content", "liucanwen");
httpClient.post(url, param, new AsyncHttpResponseHandler()
{
@Override
public void onStart()
{
super.onStart();
uploadInfo.setText("正在上傳...");
}
@Override
public void onSuccess(String arg0)
{
super.onSuccess(arg0);
Log.i("ck", "success>" + arg0);
if(arg0.equals("success"))
{
Toast.makeText(MainActivity.this, "上傳成功!", 1000).show();
}
uploadInfo.setText(arg0);
}
@Override
public void onFailure(Throwable arg0, String arg1)
{
super.onFailure(arg0, arg1);
uploadInfo.setText("上傳失敗!");
}
});
} catch (FileNotFoundException e)
{
e.printStackTrace();
Toast.makeText(MainActivity.this, "上傳文件不存在!", 1000).show();
}
}
}
伺服器端代碼:
public class UploadFileServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// 創建文件項目工廠對象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設置文件上傳路徑
String upload = this.getServletContext().getRealPath("/upload/");
// 獲取系統默認的臨時文件保存路徑,該路徑為Tomcat根目錄下的temp文件夾
String temp = System.getProperty("java.io.tmpdir");
// 設置緩沖區大小為 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 設置臨時文件夾為temp
factory.setRepository(new File(temp));
// 用工廠實例化上傳組件,ServletFileUpload 用來解析文件上傳請求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
// 解析結果放在List中
try
{
List<FileItem> list = servletFileUpload.parseRequest(request);
for (FileItem item : list)
{
String name = item.getFieldName();
InputStream is = item.getInputStream();
if (name.contains("content"))
{
System.out.println(inputStream2String(is));
} else if(name.contains("file"))
{
try
{
inputStream2File(is, upload + "\" + item.getName());
} catch (Exception e)
{
e.printStackTrace();
}
}
}
out.write("success");
} catch (FileUploadException e)
{
e.printStackTrace();
out.write("failure");
}
out.flush();
out.close();
}
// 流轉化成字元串
public static String inputStream2String(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1)
{
baos.write(i);
}
return baos.toString();
}
// 流轉化成文件
public static void inputStream2File(InputStream is, String savePath)
throws Exception
{
System.out.println("文件保存路徑為:" + savePath);
File file = new File(savePath);
InputStream inputSteam = is;
BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
int f;
while ((f = fis.read()) != -1)
{
fos.write(f);
}
fos.flush();
fos.close();
fis.close();
inputSteam.close();
}
}
追問
謝謝。
手機上傳過來的東東是在哪個變數裡面的。這個方法我有在網上找到,就是不知道要怎麼用,看起來怎麼覺得沒有一個變數是跟客戶端打交道了。
IOS的要怎麼用
回答
首先你得在客戶端選中一個文件把,apk iph啥的 然後點擊「上傳」 就請求了String url = "http://192.168.0.108:8080/UploadFileServer/upload"; 一個url對吧 然後就以流的方式把文件傳輸過去,你再用spring 類似這段代碼 「@RequestMapping("/uploadPage")
@ResponseBody
public String uploadPage(Long id,@RequestParam("userfile") CommonsMultipartFile mFile){」,接下來就是里邊具體內容的處理了,上面的例子是普通的servlet。如果用spring框架就套用這個。
追問
謝謝!
我有用Spring框架,不過還不是很明白你說的,能不能再說詳細一點,還有這幾個註解要導入什麼包。Spring學的不是很多
我查過了,網上說是Struts2的過濾器過濾沒了,所以List<FileItem> list = servletFileUpload.parseRequest(request);一直為空。然後把/*改成*.action就又報錯了
回答
哦 我用的這是spring mvc struts2用的太早了,不記得了。反正中心思想就是提交流媒體到java服務端,能獲得二進制流就行 剩下的就是你怎麼運用框架了,具體你查查struts2的上傳如何使用。
C. java+flex怎麼上傳文件
關於flex上傳功能的實現依賴於FileReference類。該類實例對象的創建有兩種方法:使用var myFileReference = new FileReference(); FileReferenceList.browse()。使用browse()或者FileReference.browse()方法可以打開上傳窗口。
下面部分資源來自互聯網,一個簡單的上傳組件代碼,包括了監聽ProgressEvent,選擇的selectEvent和完成的completeEvent。為了避免硬編碼,將urlRequest路徑配置在一個xml裡面,使用了httpservice進行請求,將結果用於UrlRequest的參數。這個HttpService採用了resultFormat="e4x",那麼要求返回來值為XML類型的
Flex上傳需要兩個包apache common fileupload.jar和apache common io.jar
upload.mxml
Xml代碼
<span style="font-size: medium;"><?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Declarations>
<!-- 將非可視元素(例如服務、值對象)放在此處 -->
<mx:HTTPService id="httpService" resultFormat="e4x"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import flash.net.FileReference;
import mx.controls.Alert;
import mx.events.CloseEvent;
import flash.events.*;
private var file:FileReference;
private var filePath:String="";
private function init():void
{
Security.allowDomain("*");
file=new FileReference();
file.addEventListener(ProgressEvent.PROGRESS, onProgress);
file.addEventListener(Event.SELECT, onSelect);
file.addEventListener(Event.COMPLETE,fileUploadCompleteHandler);
httpService.url="config.xml";
httpService.showBusyCursor=true;
httpService.send();
httpService.addEventListener(ResultEvent.RESULT,hsResultHandler);
httpService.addEventListener(FaultEvent.FAULT,hsFaultHandler);
}
private function hsResultHandler(e:ResultEvent):void{
var xml:XML=e.result as XML;
filePath=xml.filepath.@path;
}
private function hsFaultHandler(e:FaultEvent):void{
Alert.show(e.fault.toString(),'http請求錯誤');
}
private function fileUploadCompleteHandler(e:Event):void{
Alert.show("上傳完成");
vBox.removeChild(bar);
}
private function upload():void
{
var imageTypes:FileFilter=new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
var docFilter:FileFilter = new FileFilter("Documents", "*.pdf;*.doc;*.txt");
//var viewFilter:FileFilter = new FileFilter("Views", "*.avi;*.flv;*.rmvb");
var allTypes:Array=new Array(imageTypes,docFilter);
// file.browse(allTypes);
file.browse();
}
private function onSelect(e:Event):void
{
Alert.show("上傳 " + file.name + " (共 " + Math.round(file.size) + " 位元組)?", "確認上傳", Alert.YES | Alert.NO, null, proceedWithUpload);
}
private function onProgress(e:ProgressEvent):void
{
lbProgress.text=" 已上傳 " + e.bytesLoaded + " 位元組,共 " + e.bytesTotal + " 位元組";
var proc:uint=e.bytesLoaded / e.bytesTotal * 100;
bar.setProgress(proc, 100);
bar.label="當前進度: " + " " + proc + "%";
}
private function proceedWithUpload(e:CloseEvent):void
{
if (e.detail == Alert.YES)
{
var request:URLRequest=new URLRequest(filePath);
try
{
file.upload(request);
}
catch (error:Error)
{
trace("上傳失敗");
}
}
}
]]>
</fx:Script>
<mx:Canvas width="100%"
height="100%"
x="10"
y="170"
fontSize="15">
<mx:VBox width="100%"
horizontalAlign="center" id="vBox">
<mx:Label id="lbProgress"
text="上傳"/>
<mx:ProgressBar id="bar"
labelPlacement="bottom"
minimum="0"
visible="true"
maximum="100"
label="當前進度: 0%"
direction="right"
mode="manual"
width="200"/>
<mx:Button label="上傳文件"
click="upload();"/>
</mx:VBox>
</mx:Canvas>
</s:Application>
</span>
config.xml
Xml代碼
<span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8"?>
<fileUploadPath>
<filepath id="filepathConfig" path="http://localhost:8080/FileUpload/upload.do"/>
</fileUploadPath> </span>
UploadServlet
Java代碼
<span style="font-size: medium;">package com.test.upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
// 定義文件的上傳路徑
private String uploadPath = "c:\\";
// 限制文件的上傳大小
private int maxPostSize = 10000000 * 1024 * 1024;
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Access !");
System.out.println(uploadPath);
// 防止中文亂碼
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 保存文件到伺服器中
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
try {
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String name = item.getName();
System.out.println(name);
try {
item.write(new File(uploadPath + name));
// SaveFile s = new SaveFile();
// s.saveFile(name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println(e.getMessage() + "結束");
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
</span>
最後,說一下Flex的FileFilter 的用法
FileFilter 類用於指示在調用 FileReference.browse() 方法、FileReferenceList.browse() 方法或調用 File、FileReference 或 FileReferenceList 對象的 browse 方法時顯示的文件瀏覽對話框中顯示用戶系統上的哪些文件。FileFilter 實例作為可選 typeFilter 參數的值傳遞給該方法。如果使用 FileFilter 實例,則會濾除 FileFilter 實例中未指定的擴展名和文件類型,即用戶無法選擇這些類型。如果未向方法傳遞任何 FileFilter 對象,則對話框中將顯示所有文件。
可以採用以下兩種方式之一使用 FileFilter 實例:
僅包含 文件擴展名的描述
包含 文件擴展名和 Macintosh 文件類型的描述
這兩種格式不能在一個 browse 方法調用中互換。必須使用其中一種格式。
可以向 browse 方法傳遞一個或多個 FileFilter 實例,如下所示:
var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
var docFilter:FileFilter = new FileFilter("Documents", "*.pdf;*.doc;*.txt");
var myFileReference:FileReference = new FileReference();
myFileReference.browse([imagesFilter, docFilter]);
或者在 AIR 應用程序中:
var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
var docFilter:FileFilter = new FileFilter("Documents", "*.pdf;*.doc;*.txt");
var myFile:File = new File();
myFile.browseForOpen("Open", [imagesFilter, docFilter]);
var imagesFilter = new air.FileFilter("Images", "*.jpg;*.gif;*.png");
var docFilter = new air.FileFilter("Documents", "*.pdf;*.doc;*.txt");
var myFile = new air.File();
myFile.browseForOpen("Open", [imagesFilter, docFilter]);
FileFilter.extension 屬性中的擴展名列表用於篩選文件瀏覽對話框中顯示的文件。該列表實際並不顯示在對話框中;若要對用戶顯示文件類型,必須在描述字元串以及擴展名列表中列出文件類型。
D. 如何利用位元組流實現java的文件上傳下載
實現上傳下載實際上就是io的轉換。舉例:
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class CCFCCBFTP {
/**
* 上傳文件
*
* @param fileName
* @param plainFilePath 明文文件路徑路徑
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上傳文件開始");
Log.info("連接遠程上傳伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("檢查文件路徑是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查詢文件路徑不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上傳文件成功:"+fileName+"。文件保存路徑:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
/**
*下載文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try {
Log.info("下載並解密文件開始");
Log.info("連接遠程下載伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
FTPFile[] fs;
ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true";
Log.info("下載文件開始。");
ftpClient.setBufferSize(1024);
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = ftpClient.retrieveFileStream(fileName);
bos = new ByteArrayOutputStream(is.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下載文件結束:"+localFilePath);
}
}
Log.info("檢查文件是否存:"+fileName+" "+bl);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon("查詢無結果,請稍後再查詢。");
return bl;
}
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}}
備註:以上方法就實現了流的二進制上傳下載轉換,只需要將伺服器連接部分調整為本地的實際ftp服務用戶名和密碼即可。
E. java 圖片自動上傳問題。。
二樓不知道在說什麼 你圖片在本地的,代碼在伺服器上運行的,本機測試做多了吧。。。。。 我也遇到了這個問題我的是高拍儀 也是只能通過<input type=file>來實現 不過這個標簽是只讀的 不能給他用JS賦值 所以要用戶點一下瀏覽把剛才拍的圖片選中手 以File的形勢傳到Action中,這顯然不行的,所以現在想了2個方案 第一個就是用高拍儀的介面 有返回圖片Base64編碼的 你可以看一下你的掃描儀是否也有提供 如果沒有的話可以在伺服器端架設一個FTP 用FTP上傳 是在不行 用VB或者VC寫控制項吧。。。
F. 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();
}