jsp和servlet如何上传和下载文件

massa163 2011-08-10 06:20:12
网上说要找common-fileup之类的包,然后就一大堆麻烦的操作,请问有什么比这个简便的方法
...全文
425 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
罗某某 2011-08-14
  • 打赏
  • 举报
回复
联系这个邮箱,给你全部。chittyjazz@sina.com
JAVAJKjiankeJK 2011-08-12
  • 打赏
  • 举报
回复
需要:jsmartcom_zh_CN.jar
这个最简单

jsp:
<a href="s.do?path=<%=this.getServletContext().getRealPath("/images/pagerror.gif") %>">下载</a>

action:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String filepath=request.getParameter("path");
try {
String filename=new String(filepath.getBytes("gbk"),"ISO-8859-1");
SmartUpload download=new SmartUpload();

download.initialize(this.getServlet().getServletConfig(), request, response);
download.setContentDisposition(null);
download.downloadFile(filepath, filename);

System.out.println("okokokok");

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
siwanwengbin 2011-08-12
  • 打赏
  • 举报
回复
<a href="URL">download</a>
suki3100 2011-08-11
  • 打赏
  • 举报
回复
在jsp页面上一定要加入enctype="multipart/form-data" 这个。要不然就会报错。
至于Servlet 如何上传/和下载 去百度下,网上各种各样的实现方式很多。
飓风zj 2011-08-11
  • 打赏
  • 举报
回复
xindrace 2011-08-10
  • 打赏
  • 举报
回复
需要这两个包
commons-fileupload-1.2.1.jar
commons-io-1.4.jar


上面是上传 下面是下载
////解决乱码问题
request.setCharacterEncoding("utf-8");
//获得id
String id = request.getParameter("id");

UploadService service = new UploadService();
UserUpload userupload = service.UUIDfile(id);

String UUIDfilename = userupload.getUUIDfilename();


User user = (User) request.getSession().getAttribute("user");


//约定一个存放文件的目录 获得目录的绝对路径
String dirPath = getServletContext().getRealPath("/WEB-INF/upload");
//将路径加上用户名
dirPath = dirPath +"\\"+ user.getUsername()+"\\"+UUIDfilename;
//创建文件必要的文件夹
File dir = new File(dirPath);

//通知浏览器以下载的方式打开(必须写在流的前面)
response.setHeader("content-type", "application/octet-stream");
//给一个字符串编码,用相关的字符集
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(userupload.getFilename(), "utf-8"));

//获得流
InputStream in = new FileInputStream(dir);
OutputStream out = response.getOutputStream();

//流的对拷
Streams.copy(in, out, true);
xindrace 2011-08-10
  • 打赏
  • 举报
回复
//解决乱码问题
request.setCharacterEncoding("utf-8");

//1.创建解析工厂
FileItemFactory factory = new DiskFileItemFactory();
//2.创建用于解析request的FileUpload
ServletFileUpload upload = new ServletFileUpload(factory);

//3.判断一下是否为文件上传表单
if(!upload.isMultipartContent(request)){
request.setAttribute("message", "不是文件上传表单");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}

//4.解析
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
throw new UploadException(e);
}
String username = null;
//5.遍历
for(FileItem item : items){
//判断是否为普通字符
if(item.isFormField()){
username = item.getString("utf-8");
System.out.println(item.getFieldName()+"----------"+item.getString("utf-8"));
}else{

//上传字段
//获得字段名
String name = item.getFieldName();
System.out.println(name);
//获得文件名
String fileName = item.getName();
//切割文件名
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);



//判断文件是否上传过
UploadService service = new UploadService();
boolean b = service.filefind(username, fileName);
if(!b){
request.setAttribute("message", service.getFileErr());
request.getRequestDispatcher("/WEB-INF/jsp/uploadform.jsp").forward(request, response);
return;
}


//将文件名加上唯一的标识 保证文件名不重复
String UUIDfileName = UUID.randomUUID().toString()+"_"+fileName;


//约定一个存放文件的目录 获得目录的绝对路径
String dirPath = getServletContext().getRealPath("/WEB-INF/upload");
//将路径加上用户名
dirPath = dirPath +"\\"+ username;
//创建文件必要的文件夹
File dir = new File(dirPath);
dir.mkdirs();
//创建文件对象
File file = new File(dir, UUIDfileName);
//创建文件
file.createNewFile();
//获得流
InputStream in = item.getInputStream();
OutputStream out = new FileOutputStream(file);

//流的对拷
Streams.copy(in, out, true);
Hel1C 2011-08-10
  • 打赏
  • 举报
回复
上传必须要 fileupload包和配套的io包
LMAOhuaNL 2011-08-10
  • 打赏
  • 举报
回复

如下用流上传下载的(转载的)
1.jsp页面
<s:form action="fileAction" namespace="/file" method="POST" enctype="multipart/form-data">
<!-- name为后台对应的参数名称 -->
<s:file name="files" label="file1"></s:file>
<s:file name="files" label="file2"></s:file>
<s:file name="files" label="file3"></s:file>
<s:submit value="提交" id="submitBut"></s:submit>
</s:form>
2.Action
//单个文件上传可以用 File files,String filesFileName,String filesContentType
//名称要与jsp中的name相同(三个变量都要生成get,set)
private File[] files;
// 要以File[]变量名开头
private String[] filesFileName;
// 要以File[]变量名开头
private String[] filesContentType;

private ServletContext servletContext;

//Action调用的上传文件方法
public String execute() {
ServletContext servletContext = ServletActionContext.getServletContext();
String dataDir = servletContext.getRealPath("/file/upload");
System.out.println(dataDir);
for (int i = 0; i < files.length; i++) {
File saveFile = new File(dataDir, filesFileName[i]);
files[i].renameTo(saveFile);
}
return "success";
}
3.配置上传文件临时文件夹(在struts.xml中配置)
<constant name="struts.multipart.saveDir" value="c:/temp"/>
文件下载
1.下载的url(到Action)
<a href="${pageContext.request.contextPath}/file/fileAction!down.action">下载</a>
2.struts.xml配置
<package name="file" namespace="/file" extends="struts-default">
<action name="fileAction" class="com.struts2.file.FileAction">
<!-- 下载文件配置 -->
<!--type 为 stream 应用 StreamResult 处理-->
<result name="down" type="stream">
<!--
不管实际类型,待下载文件 ContentType 统一指定为 application/octet-stream
默认为 text/plain
-->
<param name="contentType">application/octet-stream</param>
<!--
默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,
比如这里就是 getInputStream() 来获取下载文件的内容,意味着你的 Action 要有这个方法
-->
<param name="inputName">inputStream</param>
<!--
默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文
件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,
这里使用的是动态文件名,${fileName}, 它将通过 Action 的 getFileName() 获得文件名
-->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 输出时缓冲区的大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
3.Action
//Action调用的下载文件方法
public String down() {
return "down";
}

//获得下载文件的内容,可以直接读入一个物理文件或从数据库中获取内容
public InputStream getInputStream() throws Exception {
String dir = servletContext.getRealPath("/file/upload");
File file = new File(dir, "icon.png");
if (file.exists()) {
//下载文件
return new FileInputStream(file);

//和 Servlet 中不一样,这里我们不需对输出的中文转码为 ISO8859-1
//将内容(Struts2 文件下载测试)直接写入文件,下载的文件名必须是文本(txt)类型
//return new ByteArrayInputStream("Struts2 文件下载测试".getBytes());
}
return null;
}

// 对于配置中的 ${fileName}, 获得下载保存时的文件名
public String getFileName() {
String fileName ="图标.png";
try {
// 中文文件名也是需要转码为 ISO8859-1,否则乱码
return new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "icon.png";
}
}
underhiswing 2011-08-10
  • 打赏
  • 举报
回复
用IO流 就不需要 那些包了吧

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧