Java 上传下载

(1) Java Servlet 实现

  1.上传

    1) 前端页面写法

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.test.action.FileBean"%>
<%@page import="com.test.action.DB"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'upload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    
    	<form action="/abc/app1/file" method="post" enctype="multipart/form-data">
    	
    		选择文件1:<input type="file" name="sourceFile" style="width: 70" value="浏览">
    		<br/>
    		选择文件2:<input type="file" name="sourceFile" style="width: 70" value="浏览">
    		<br/>
    		选择文件3:<input type="file" name="sourceFile" style="width: 70" value="浏览">
    		<br/>
    		
    		<input type="submit" value="上传" style="width: 50">
    	
    	</form>
    <div> 
    <table>
    <tr>
    <td style="width: 82%">文件名称</td><td>下载选项</td>
    </tr>
    </table>
    	<%!private List<FileBean> getFiles(){
DB db=new DB();
List<FileBean> al = db.fileBeans();
return al;} %>
<table>
    <%
    List<FileBean>  al = getFiles(); 
     for(int i = 0; i < al.size(); i++){
      %><tr><td style="width: 90%">
     <span style="width: 30"><%=al.get(i).getName()%></span></td>
    <td> <a href="/abc/app1/download?name=<%=al.get(i).getName()%>">下载</a><td></tr>
 <% }%>
    
    </table>
    </div>
  </body>
</html>

    2) 后台servlet (FileUtils.copyFile(sourceFile[i], newFile)需要包commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar.这两个文件可以从http://commons.apache.org/下载)

package com.test.action;

import java.io.File;
import java.io.IOException;

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

public class FileAction {

	private String dol;
	private File[] sourceFile;
	private String[] sourceFileFileName;
	public String getDol() {
		return dol;
	}
	public void setDol(String dol) {
		this.dol = dol;
	}
	public File[] getSourceFile() {
		return sourceFile;
	}
	public void setSourceFile(File[] sourceFile) {
		this.sourceFile = sourceFile;
	}
	public String[] getSourceFileFileName() {
		return sourceFileFileName;
	}
	public void setSourceFileFileName(String[] sourceFileFileName) {
		this.sourceFileFileName = sourceFileFileName;
	}

	public String execute() {
		System.out.println("shangchuan...");
		String path = ServletActionContext.getServletContext().getRealPath(
				"/imgs");
		path += File.separator;
		try {
			for (int i = 0; i < sourceFile.length; i++) {
				File newFile = new File(path + this.sourceFileFileName[i]);
				DB db = new DB(newFile.toString());
				if(db.addFile()){
					System.out.println("true");
//					byte[] b=new byte[1222];
//					InputStream in=new FileInputStream(path);
//					OutputStream out=new FileOutputStream(path);
//					while(in.read(b)>0){
//						out.write(b);
//					}
					FileUtils.copyFile(sourceFile[i], newFile);
				}
				if(!db.addFile()){
					System.out.println("false");
					this.dol="0";
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "upload";
	}
	
}

  2.下载

    1) 前端页面写法(只要有链接到后台servlet就可以,如上↑↑)

    2) 后台servlet

package com.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
/**
 * 实现java的下载功能,先读取资源流,然后再利用response.getOutputStream()输出,此类是servlet;
 * @author Administrator
 *
 */
public class FileDownServlet extends HttpServlet {
	private static final String CONTENT_TYPE = "text/html; charset=GBK";

	// Initialize global variables
	public void init() throws ServletException {
	}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	System.out.println("service");
	doGet(req,resp);
}
	// Process the HTTP Get request
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType(CONTENT_TYPE);
		// 得到下载文件的名字
		// String filename=request.getParameter("filename");
		// 解决中文乱码问题
		// String filename=new
		// String(request.getParameter("filename").getBytes("iso-8859-1"),"gbk");
		String filename = "rss.xml";
		// 创建file对象
		File file = new File("F://" + filename);
		// 设置response的编码方式
		response.setContentType("application/x-msdownload");
		// 写明要下载的文件的大小
		response.setContentLength((int) file.length());
		// 设置附加文件名
		// response.setHeader("Content-Disposition","attachment;filename="+filename);
		// 解决中文乱码
		response.setHeader("Content-Disposition", "attachment;filename="
				+ new String(filename.getBytes("gbk"), "iso-8859-1"));
		// 读出文件到i/o流
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream buff = new BufferedInputStream(fis);

		byte[] b = new byte[1024];// 相当于我们的缓存
		long k = 0;// 该值用于计算当前实际下载了多少字节
		// 从response对象中得到输出流,准备下载
		OutputStream myout = response.getOutputStream();
		// 开始循环下载

		while (k < file.length()) {
			int j = buff.read(b, 0, 1024);
			k += j;
			// 将b中的数据写到客户端的内存
			myout.write(b, 0, j);
		}
		// 将写入到客户端的内存的数据,刷新到磁盘
		myout.flush();

	}
	// Process the HTTP Post request
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doPost");
		doGet(request, response);
	}

	// Clean up resources
	public void destroy() {
	}
}

(2) Struts 功能实现

  1.上传

    1) 前端页面写法

    2) 后台action(同上java的上传雷同)

  2.下载

   1) 前端页面写法(只要有链接到后台servlet就可以)

   2) 后台action

package com.test.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport{
	private String name;
    private String DownloadFileName;
	private InputStream inputStream;  
  
    public String getDownloadFileName() {
		return DownloadFileName;
	}
	public void setDownloadFileName(String downloadFileName) {
		DownloadFileName = downloadFileName;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override  
    public String execute() throws Exception {  
		String temp=this.name;
		String tem= new String(temp.getBytes("ISO8859-1"),"utf-8");
		String path="F:\\apache-tomcat-6.0.36\\webapps\\abc\\imgs\\"+tem;
		String filename=tem;
        inputStream = new FileInputStream(new File(path));  
        this.DownloadFileName=new String(filename.getBytes(),"ISO8859-1");
        return SUCCESS;  
    }  
    public InputStream getInputStream() {  
        return inputStream;  
    }  
    public void setInputStream(InputStream inputStream) {  
        this.inputStream = inputStream;  
    }  
}
  3) struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<constant name="struts.multipart.maxSize" value="104857600"></constant>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="false" />
	<package name="app" namespace="/app1" extends="struts-default">
		
		<action name="download" class="com.test.action.DownloadAction">
			<result name="success" type="stream">
				<param name="contentType">application/octet-stream</param>
				<param name="inputName">inputStream</param>
				<param name="contentDisposition">attachment;filename=${DownloadFileName}</param>
				<param name="bufferSize">1024</param>
			</result>
		</action>
		
	</package>
</struts>    

(2) 使用io的开源项目完成上传文件的功能

      1.  jsp写法

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="/web/ManageServlet" method="post" enctype="multipart/form-data">
		文件:<input type="file" name="videofile"/><!-- 此处的参数名称不重要 -->
		<input type="submit" value=" 提 交 "/>
	</form>
</body>
</html>

      2. 后台servelt写法

package cn.itcast.servlet;

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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String title = request.getParameter("title");		
		String timelength = request.getParameter("timelength");
		System.out.println("视频名称:"+ title);
		System.out.println("时长:"+ timelength);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(isMultipart){
			try{
				FileItemFactory factory = new DiskFileItemFactory();
//                File filetemp = new File("d:/a");
//                if(!filetemp.exists()){filetemp.mkdirs();}
//                factory.setRepository(new File("d:/a")); //设置临时目录
//                factory.setSizeThreshold(1024*8); //8k的缓冲区,文件大于8K则保存到临时目录
                  ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
//                upload.setFileSizeMax(1024 * 1024 * 10*2);// 设置每个文件最大为20M
//                upload.setSizeMax(1024 * 1024 * 100);// 一共最多能上传100M
 List<FileItem> items = upload.parseRequest(request);
				String dir = request.getSession().getServletContext().getRealPath("/files");
				File dirFile = new File(dir);
				if(!dirFile.exists()) dirFile.mkdirs();
				for(FileItem item : items){
					if(item.isFormField()) {//如果文本类型参数
						String name = item.getFieldName();
						String value = item.getString("UTF-8");
						System.out.println(name+ "="+ value);
					}else{//如果文件类型参数
						System.out.println(dir);
						File saveFile = new File(dirFile, item.getName());
						item.write(saveFile);
					}
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			doGet(request, response);
		}
	}

}

      3. 所需要的包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值