我想做一个上传文件到服务器,并自动显示出来然后下载,应该怎么办哟??希望高手能指点一下。谢谢!!
解决方案 »
- showModelessDialog问题
- 用MySql 的服务器管理工具如何 设置表字段的惟一性
- 求Jsp新闻发布系统后台用的eWebEditor编辑器
- jasper报表-斜线怎么显示
- 有关多线程顺序执行的问题
- 救命啊!!!!!!!!!!!!!!为什么JSP中的<%%>不起作用??
- 为什么不能取得带()之类的参数
- 一个Session的问题,请问
- SOS![存储过程]出现了:第 1 行: '@P2' 附近有语法错误
- 求助!一个关闭IE的问题。
- AJAX+STRUTS+SPRING+hibernate如何实现AJAX直接调用ACTION的方法!,请高人指点
- Tomcat中8009端口(使用AJP协议)的connector有没有maxThreads,minSpareThreads,maxSpareThreads等属性啊?
1.RunningUpLoader上传Bean
首先是RunningUpLoader.java,代码有些多,因为我是自己来解析输入流的。package testupload;
import java.io.*;
import javax.servlet.http.HttpServletRequest;
public class RunningUpLoader {
public RunningUpLoader() {
} /**
* 上传文件
* @param request HttpServletRequest Servlet的请求对象
* @param name String 要上传的文件在表单中的参数名
* @param fileName String 保存在服务器上的文件名
* @throws IOException
*/
public void doUpload(HttpServletRequest request, String name,String fileName) throws
IOException {
InputStream in = request.getInputStream();
byte[] buffer = getFileContent(name,in);
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(buffer,0,buffer.length-1);
fos.close();
} /**
* 获取上传的文件buffer,结尾处将多一个换行符
* @param name String 文件上传参数的名字
* @param is InputStream 服务器对话的输入流
* @return byte[] 返回获取的文件的buffer,结尾处多一个换行符
* @throws IOException
*/
private byte[] getFileContent(String name, InputStream is) throws IOException{
int index;
boolean isEnd = false;
byte[] lineSeparatorByte;
byte[] lineData;
String content_disposition;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedInputStream bis = new BufferedInputStream(is); lineSeparatorByte = readStreamLine(bis);
while(!isEnd) {
lineData = readStreamLine(bis);
if(lineData == null) {
break;
}
content_disposition = new String(lineData,"ASCII");
index = content_disposition.indexOf("name=\"" + name + "\"");
if (index >= 0 && index < content_disposition.length()) {
System.out.println(readStreamLineAsString(bis)); // skip a line
System.out.println(readStreamLineAsString(bis)); // skip a line while ((lineData = readStreamLine(bis)) != null) {
System.out.println(new String(lineData));
if (isByteArraystartWith(lineData, lineSeparatorByte)) { // end
isEnd = true;
break;
} else {
bos.write(lineData);
}
}
}else {
lineData = readStreamLine(bis);
if(lineData == null)
return null;
System.out.println(new String(lineData,"ASCII"));
while(!isByteArraystartWith(lineData, lineSeparatorByte)) {
lineData = readStreamLine(bis);
if(lineData == null)
return null;
System.out.println(new String(lineData,"ASCII"));
}
}
}
return bos.toByteArray();
} private byte[] readStreamLine(BufferedInputStream in) throws IOException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b = in.read();
if(b== -1)
return null;
while(b != -1 && b != '\n') {
bos.write(b);
b = in.read();
}
return bos.toByteArray();
} private String readStreamLineAsString(BufferedInputStream in) throws IOException {
return new String(readStreamLine(in),"ASCII");
} private boolean isByteArraystartWith(byte[] arr,byte[] pat) {
int i;
if(arr == null || pat == null)
return false;
if(arr.length < pat.length)
return false;
for(i=0;i<pat.length;i++) {
if(arr[i] != pat[i])
return false;
}
return true;
}
}
上传文件文件的时候,需要在之前的html中增加一个form表单,里面需要有个<input type="file" name="fileUpload" >的输入按钮。这样,浏览器才会将要上传的文件递交给服务器。 其中name="fileUpload"的名字,就是RunnningUpLoader.doUpload函数中的name参数。使用的时候直接用bean就OK了。比如upload.jsp如下:<jsp:useBean id="upBean" scope="page" class="testupload.RunningUpLoader" /><%upBean.doUpload(request,"fileupload","runningUpLoad.txt");%> 2. RunningDownLoader下载Bean
package testupload;
import java.io.*;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;public class RunningDownLoader {
public RunningDownLoader() {
} public void doDownload(HttpServletResponse response, String filePath,String fileName) throws
IOException {
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//设置为下载application/x-download
System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
String filenamedownload = filePath;
String filenamedisplay = fileName;//系统解决方案.txt
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay); OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload); byte[] b = new byte[1024];
int i = 0; while((i = fis.read(b)) > 0)
{
output.write(b, 0, i);
}
output.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
} } }
下载文件,最好是做到Servlet上。直接在Servlet的doGet下面增加如下代码即可//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
RunningDownLoader downloader= new RunningDownLoader();
downloader.doDownload(response,"E:\\MyProjects\\testupload.rar","upload.bin");
}
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*,java.text.SimpleDateFormat,java.util.*,java.io.*,com.jspsmart.upload.*" errorPage="" %>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
mySmartUpload.initialize(pageContext);
mySmartUpload.setMaxFileSize(10000000);
mySmartUpload.setTotalMaxFileSize(30000000);
mySmartUpload.setDeniedFilesList("dll,,");
// Upload
mySmartUpload.upload(); // Select each file
for (int i=0;i<mySmartUpload.getFiles().getCount();i++){ // Retreive the current file
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i); // Save it only if this file exists
if (!myFile.isMissing()) { // Save the files with its original names in a virtual path of the web server
myFile.saveAs("/upload/" + myFile.getFileName());
// myFile.saveAs("/upload/" + myFile.getFileName(), mySmartUpload.SAVE_VIRTUAL); // sample with a physical path
// myFile.saveAs("c:\\temp\\" + myFile.getFileName(), mySmartUpload.SAVE_PHYSICAL); // Display the properties of the current file
tt=tt+myFile.getFileName()+"&";
} }
下载文件程序:download.jsp
<%@ page import="com.jspsmart.upload.*" contentType="text/html; charset=gb2312"%><%@ include file="inc/trans1.inc"%><%
// 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 初始化
String str=trans(request.getParameter("str"));
su.initialize(pageContext);
// 设定contentDisposition为null以禁止浏览器自动打开文件,
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
//doc时,浏览器将自动用word打开它。扩展名为pdf时,
//浏览器将用acrobat打开。
su.setContentDisposition(null);
// 下载文件
su.downloadFile("/upload/"+str);
%>
再写一个上传页面:1.html
<HTML>
<BODY BGCOLOR="white"><H1>jspSmartUpload : Sample 2</H1>
<HR><FORM METHOD="POST" ACTION="download.jsp" ENCTYPE="multipart/form-data">
<INPUT TYPE="FILE" NAME="FILE1" SIZE="50"><BR>
<INPUT TYPE="FILE" NAME="FILE2" SIZE="50"><BR>
<INPUT TYPE="FILE" NAME="FILE3" SIZE="50"><BR>
<INPUT TYPE="FILE" NAME="FILE4" SIZE="50"><BR>
<INPUT TYPE="SUBMIT" VALUE="Upload">
</FORM></BODY>
</HTML>
这是最简单的组件,上传doc文件很好用
<form action="" method="POST" enctype="multipart/form-data">还要用上fileupload包,到sun公司去下。再去看看“一个关于文件上传的问题 ”这个贴,里面代码有你要用的上。