1.下載簡(jiǎn)單,無非是把服務(wù)器上的文件或者數(shù)據(jù)庫中的BLob(或其他二進(jìn)制型),用流讀出來,然后寫到客戶端即可,要注意 ContentType。
成都創(chuàng)新互聯(lián)公司服務(wù)項(xiàng)目包括嘉祥網(wǎng)站建設(shè)、嘉祥網(wǎng)站制作、嘉祥網(wǎng)頁制作以及嘉祥網(wǎng)絡(luò)營(yíng)銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,嘉祥網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到嘉祥省份的部分城市,未來相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
2.上傳,可以用Apache Commons Upload等開源工具,或者自己寫:
form要用enctype="multipart/form-data"
然后服務(wù)器端也是用IO把客戶端提交的文件流讀入,然后寫到服務(wù)器的文件系統(tǒng)或者數(shù)據(jù)庫里。不同的數(shù)據(jù)庫對(duì)Lob字段操作可能有所不同,建議用Hibernate,JPA等成熟的ORM框架,可以不考慮數(shù)據(jù)庫細(xì)節(jié)。
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;
/**
* 完成文件上傳 (不是解析上傳內(nèi)容,因?yàn)樯蟼鲀?nèi)容 由fileUpload攔截器負(fù)責(zé)解析)
*
* @author seawind
*
*/
public class UploadAction extends ActionSupport {
// 接收上傳內(nèi)容
// 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校驗(yàn)器 完成校驗(yàn)
// 沒有上傳文件
return NONE;
}
// 將上傳文件 保存到服務(wù)器端
// 源文件 upload
// 目標(biāo)文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload") + "/" + uploadFileName);
// 文件復(fù)制 使用commons-io包 提供 工具類
FileUtils.copyFile(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 {
// 接收多文件上傳參數(shù),提供數(shù)組接收就可以了
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++) {
// 循環(huán)完成上傳
File srcFile = upload[i];
String filename = uploadFileName[i];
// 定義目標(biāo)文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload" + "/" + filename));
FileUtils.copyFile(srcFile, destFile);
}
return NONE;
}
}
用輸出流 接受 一個(gè)下載地址的網(wǎng)絡(luò)流
然后將這個(gè)輸出流 保存到本地一個(gè)文件 后綴與下載地址的后綴相同··
上傳的話 將某個(gè)文件流 轉(zhuǎn)成字節(jié)流 上傳到某個(gè)webservice方法里
-------要代碼來代碼
URL url=new URL("");
URLConnection uc=url.openConnection();
InputStream in=uc.getInputStream();
BufferedInputStream bis=new BufferedInputStream(in);
FileOutputStream ft=new FileOutputStream("E://1.rar");
這是下載 上傳太麻煩就不給寫了
FileInputStream fin = new FileInputStream(new File("你的文件地址"));
OutputStream out = 你的目標(biāo)流地址,可以是Socket的Output流,也可以是http的Output流,等等
byte[] b = new byte[65535]; // 一次讀取多少字節(jié)
int read = -1;
while(-1 != (read = fin.read(b))){
out.write(b,0,read);
}
利用struts2的上傳下載
package?com.java.action;
import?java.io.File;
import?java.io.FileInputStream;
import?java.io.FileNotFoundException;
import?java.io.IOException;
import?java.io.InputStream;
import?java.io.UnsupportedEncodingException;
import?java.net.URLEncoder;
import?org.apache.commons.io.FileUtils;
import?org.apache.struts2.ServletActionContext;
import?com.opensymphony.xwork2.ActionSupport;
public?class?FileAction?extends?ActionSupport?{
/**
*?用于上傳的變量
*/
//封裝該文件域?qū)?yīng)的文件內(nèi)容
private?File[]?upload;
//封裝該文件域?qū)?yīng)的文件的文件名
private?String[]?uploadFileName;
//封裝該文件域?qū)?yīng)的文件的文件類型
private?String[]?uploadContentType;
/**
*?用于下載的變量
*/
private?String[]?fileNames;
private?String?fileName;
/**
*?設(shè)置getter和setter
*?@return
*/
public?String[]?getFileNames()?{
return?fileNames;
}
public?File[]?getUpload()?{
return?upload;
}
public?void?setUpload(File[]?upload)?{
this.upload?=?upload;
}
public?String[]?getUploadFileName()?{
return?uploadFileName;
}
public?void?setUploadFileName(String[]?uploadFileName)?{
this.uploadFileName?=?uploadFileName;
}
public?String[]?getUploadContentType()?{
return?uploadContentType;
}
public?void?setUploadContentType(String[]?uploadContentType)?{
this.uploadContentType?=?uploadContentType;
}
public?void?setFileNames(String[]?fileNames)?{
this.fileNames?=?fileNames;
}
public?String?getFileName()?{
return?fileName;
}
public?void?setFileName(String?fileName)?{
this.fileName?=?fileName;
}
/**
*?用于上傳文件的方法
*?@return
*/
public?String?upload(){
//設(shè)置文件上傳到的位置
String?path?=?ServletActionContext.getServletContext().getRealPath("/file");
//設(shè)置文件目標(biāo)
try?{
for?(int?i?=?0;?i??upload.length;?i++)?{
File?target?=?new?File(path,?uploadFileName[i]);
FileUtils.copyFile(upload[i],?target);
}
return?SUCCESS;
}?catch?(IOException?e)?{
e.printStackTrace();
}
return?INPUT;
}
/**
*?得到所有上傳的文件的名稱
*?@return
*/
public?String?fileList(){
String?path?=?ServletActionContext.getServletContext().getRealPath("/file");
fileNames?=?new?File(path).list();
return?SUCCESS;
}
/**
*?用于下載文件的方法
*?@return
*/
public?InputStream?getInputStream(){
if(fileName==null?||?fileName.isEmpty())?return?null;
String?path?=?ServletActionContext.getServletContext().getRealPath("/file");
try?{
return?new?FileInputStream(new?File(path,fileName));
}?catch?(FileNotFoundException?e)?{
e.printStackTrace();
}
return?null;
}
public?String?getContentDisposition(){
try?{
if(fileName==null||fileName.isEmpty()){
return?"inline";
}
return?"attachment;filename="+URLEncoder.encode(fileName,?"UTF-8");
}?catch?(UnsupportedEncodingException?e)?{
e.printStackTrace();
}
return?"inline";
}
}
比java的io方便多了
/**
上傳文件
*/
public class FileAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
FileForm fileform = (FileForm) form;
//取得請(qǐng)求的文件集合
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();//創(chuàng)建目錄
}
String fileName=file.getFileName();
//創(chuàng)建一個(gè)文件輸入流
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();
}
}
}
/**
下載文件
*/
頁面一開始進(jìn)去action,action負(fù)責(zé)把file文件夾下的所有文件讀入一個(gè)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;icontents.length;i++){
FullPath=contents.getName();
list.add(FullPath);
//System.out.println(FullPath);
}
request.setAttribute("list",list);
ActionForward forward=new ActionForward("/download.jsp");
return forward;
然后進(jìn)入download.jsp中,這個(gè)頁面主要負(fù)責(zé)把所有文件顯示,并提供下載連接,代碼如下:
%@ 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;ilist.size();i++)
{
String a=java.net.URLEncoder.encode((String)list.get(i));
out.print("a href=./loaded.do?name="+a+""+list.get(i)+"/abr");
}
%
/body
/html
注意,下劃線畫中的代碼的作用,就是解決問題的所在。
接下來可以直接傳入到loadedaction中,也可以通過一個(gè)form,我演示的是通過一個(gè)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"));
如果不這樣做你將要下載的文件名是亂碼。
當(dāng)前文章:上傳下載文件java代碼 上傳下載文件java代碼錯(cuò)誤
網(wǎng)站地址:http://chinadenli.net/article0/hgcsoo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、標(biāo)簽優(yōu)化、面包屑導(dǎo)航、品牌網(wǎng)站設(shè)計(jì)、外貿(mào)建站、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)