java实现文件上传下载
有没有那本书讲过如何用java实现文件上传下载啊?
------解决方案--------------------[code=Java][/code]import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDownload extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
String fname = "test.xls";
response.setCharacterEncoding("UTF-8");
fname = java.net.URLEncoder.encode(fname, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+fname);
response.setContentType("application/msexcel");// 定义输出类型
} catch (Exception e) {
System.out.println(e);
}
}
}
//上面是下载用的servlet
[code=Java][/code]import java.io.File;
import
java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws
IOException,
ServletException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator items;
try {
items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem item = (FileItem) items.next();
if (!item.isFormField()) {
//取出上传文件的文件名称
String name = item.getName();
String fileName = name.substring(name.lastIndexOf('\\')+1,name.length());
String path = request.getRealPath("file")+File.separatorChar+fileName;
//上传文件
File uploadedFile = new File(path);
item.write(uploadedFile);
//打印上传成功信息
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
out.print("<font size='2'>上传的文件为:"+name+"<br>");
out.print("保存的地址为:"+path+"</font>");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 上面是 上传的servlet
希望能给楼主一点帮助,我和你一样 也是在学习中
------解决方案--------------------文件上传类:MoqUploadBean.java
package net.moq.www;
import java.io.*;
import java.util.*;
import javax.servlet