Java实现上传和下载功能(支持多个文件同时上传)

文件上传一直是Web项目中必不可少的一项功能。

项目结构如下:(这是我之前创建的SSM整合的框架项目,在这上面添加文件上传与下载)

主要的是FileUploadController,doupload.jsp,up.jsp,springmvc.xml

1.先编写up.jsp

<form action="doupload.jsp" enctype="multipart/form-data" method="post">
 <p>上传者:<input type="text" name="user"></p>
 <p>选择文件:<input type="file" name="nfile"></p>
 <p>选择文件:<input type="file" name="nfile1"></p>
 <p><input type="submit" value="提交"></p>
</form>

以上便是up.jsp的核心代码;

2.编写doupload.jsp

<%
 request.setCharacterEncoding("utf-8");
 String uploadFileName = ""; //上传的文件名
 String fieldName = ""; //表单字段元素的name属性值
 //请求信息中的内容是否是multipart类型
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 //上传文件的存储路径(服务器文件系统上的绝对文件路径)
 String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" );
 if (isMultipart) {
 FileItemFactory factory = new DiskFileItemFactory();
 ServletFileUpload upload = new ServletFileUpload(factory);
 try {
 //解析form表单中所有文件
 List<FileItem> items = upload.parseRequest(request);
 Iterator<FileItem> iter = items.iterator();
 while (iter.hasNext()) { //依次处理每个文件
 FileItem item = (FileItem) iter.next();
 if (item.isFormField()){ //普通表单字段
 fieldName = item.getFieldName(); //表单字段的name属性值
 if (fieldName.equals("user")){
 //输出表单字段的值
 out.print(item.getString("UTF-8")+"上传了文件。<br/>");
 }
 }else{ //文件表单字段
 String fileName = item.getName();
 if (fileName != null && !fileName.equals("")) {
 File fullFile = new File(item.getName());
 File saveFile = new File(uploadFilePath, fullFile.getName());
 item.write(saveFile);
 uploadFileName = fullFile.getName();
 out.print("上传成功后的文件名是:"+uploadFileName);
 out.print("\t\t下载链接:"+"<a href='download.action?name="+uploadFileName+"'>"+uploadFileName+"</a>");
 out.print("<br/>");
 }
 }
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
%>

该页面主要是内容是,通过解析request,并设置上传路径,创建一个迭代器,先进行判空,再通过循环来实现多个文件的上传,再输出文件信息的同时打印文件下载路径。

效果图:

3.编写FilterController实现文件下载的功能(相对上传比较简单):

@Controller
public class FileUploadController {
 @RequestMapping(value="/download")
 public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception {
 //下载显示的文件名,解决中文名称乱码问题
 filename=new String(filename.getBytes("iso-8859-1"),"UTF-8");
 //下载文件路径
 String path = request.getServletContext().getRealPath("/upload/");
 File file = new File(path + File.separator + filename);
 HttpHeaders headers = new HttpHeaders();
 //下载显示的文件名,解决中文名称乱码问题
 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
 //通知浏览器以attachment(下载方式)打开图片
 headers.setContentDispositionFormData("Content-Disposition", downloadFielName);
 //application/octet-stream : 二进制流数据(最常见的文件下载)。
 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
 return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
 headers, HttpStatus.CREATED);
 }
}

4.实现上传文件的功能还需要在springmvc中配置bean:

<bean id="multipartResolver"
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!-- 上传文件大小上限,单位为字节(10MB) -->
 <property name="maxUploadSize">
 <value>10485760</value>
 </property>
 <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
 <property name="defaultEncoding">
 <value>UTF-8</value>
 </property>
</bean>

完整代码如下:

up.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <title>File控件</title>
 </head>

 <body>
 <form action="doupload.jsp" enctype="multipart/form-data" method="post">
 <p>上传者:<input type="text" name="user"></p>
 <p>选择文件:<input type="file" name="nfile"></p>
 <p>选择文件:<input type="file" name="nfile1"></p>
 <p><input type="submit" value="提交"></p>
 </form>
 </body>
</html>

doupload.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import="java.io.*,java.util.*"%>
<%@page import="org.apache.commons.fileupload.*"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>上传处理页面</title>
</head>
<body>
<%
 request.setCharacterEncoding("utf-8");
 String uploadFileName = ""; //上传的文件名
 String fieldName = ""; //表单字段元素的name属性值
 //请求信息中的内容是否是multipart类型
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 //上传文件的存储路径(服务器文件系统上的绝对文件路径)
 String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" );
 if (isMultipart) {
 FileItemFactory factory = new DiskFileItemFactory();
 ServletFileUpload upload = new ServletFileUpload(factory);
 try {
 //解析form表单中所有文件
 List<FileItem> items = upload.parseRequest(request);
 Iterator<FileItem> iter = items.iterator();
 while (iter.hasNext()) { //依次处理每个文件
 FileItem item = (FileItem) iter.next();
 if (item.isFormField()){ //普通表单字段
 fieldName = item.getFieldName(); //表单字段的name属性值
 if (fieldName.equals("user")){
 //输出表单字段的值
 out.print(item.getString("UTF-8")+"上传了文件。<br/>");
 }
 }else{ //文件表单字段
 String fileName = item.getName();
 if (fileName != null && !fileName.equals("")) {
 File fullFile = new File(item.getName());
 File saveFile = new File(uploadFilePath, fullFile.getName());
 item.write(saveFile);
 uploadFileName = fullFile.getName();
 out.print("上传成功后的文件名是:"+uploadFileName);
 out.print("\t\t下载链接:"+"<a href='download.action?name="+uploadFileName+"'>"+uploadFileName+"</a>");
 out.print("<br/>");
 }
 }
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
%>
</body>
</html>

FileUploadController.java

package ssm.me.controller;

import java.io.File;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

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;
import org.apache.commons.io.FileUtils;
import org.junit.runners.Parameterized.Parameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {
 @RequestMapping(value="/download")
 public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception {
 //下载显示的文件名,解决中文名称乱码问题
 filename=new String(filename.getBytes("iso-8859-1"),"UTF-8");
 //下载文件路径
 String path = request.getServletContext().getRealPath("/upload/");
 File file = new File(path + File.separator + filename);
 HttpHeaders headers = new HttpHeaders();
 //下载显示的文件名,解决中文名称乱码问题
 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
 //通知浏览器以attachment(下载方式)打开图片
 headers.setContentDispositionFormData("Content-Disposition", downloadFielName);
 //application/octet-stream : 二进制流数据(最常见的文件下载)。
 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
 return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
 headers, HttpStatus.CREATED);
 }
}

SpringMVC.xml(仅供参考,有的地方不可以照搬)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx.xsd">
 <!-- 一个用于自动配置注解的注解配置 -->
 <mvc:annotation-driven></mvc:annotation-driven>
 <!-- 扫描该包下面所有的Controller -->
 <context:component-scan base-package="ssm.me.controller"></context:component-scan>
 <!-- 视图解析器 -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
 <bean id="multipartResolver"
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!-- 上传文件大小上限,单位为字节(10MB) -->
 <property name="maxUploadSize">
 <value>10485760</value>
 </property>
 <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
 <property name="defaultEncoding">
 <value>UTF-8</value>
 </property>
 </bean>

</beans> 

web.xml(仅供参考,有的地方不可以照搬)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>Student</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>springmvc</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <!-- 初始化参数 -->
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:springmvc.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>springmvc</servlet-name>
 <url-pattern>*.action</url-pattern>
 </servlet-mapping>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:spring/applicationContext-*.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
</web-app>

以上便为文件上传和下载的全部代码,博主亲测过,没有问题。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Java Spring MVC 上传下载文件配置及controller方法详解

    下载: 1.在spring-mvc中配置(用于100M以下的文件下载) <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!--配置下载返回类型--> <bean class="or

  • java中struts2实现文件上传下载功能实例解析

    本文实例讲述了java中struts2实现文件上传下载功能实现方法.分享给大家供大家参考.具体分析如下: 1.文件上传 首先是jsp页面的代码 在jsp页面中定义一个上传标签 复制代码 代码如下: <tr>      <td align="right" bgcolor="#F5F8F9"><b>附件:</b></td>      <td bgcolor="#FFFFFF">

  • java实现FTP文件上传与文件下载

    本文实例为大家分享了两种java实现FTP文件上传下载的方式,供大家参考,具体内容如下 第一种方式: package com.cloudpower.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import sun.net.TelnetInputStream; import sun.net.TelnetO

  • JavaWeb实现文件上传下载功能实例解析

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件.这个common-fileupload上传组件的jar包可以去apache官网上面下载,也可以在struts的lib文件夹下面找到,stru

  • JAVA中使用FTPClient实现文件上传下载实例代码

    在java程序开发中,ftp用的比较多,经常打交道,比如说向FTP服务器上传文件.下载文件,本文给大家介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件. 一.上传文件 原理就不介绍了,大家直接看代码吧 /** * Description: 向FTP服务器上传文件 * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@d-heaven.com)创建 * @param url F

  • JavaWeb实现文件上传下载功能实例详解

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 文件上传概述 1.文件上传的作用 例如网络硬盘!就是用来上传下载文件的. 在智联招聘上填写一个完整的简历还需要上传照片呢. 2.文件上传对页面的要求 上传文件的要求比较多,需要记一下: 必须使用表单,而不能是超链接 表单的method必须是POST,而不能是GET 表单的enctype必须是multipart/form-data 在表单中添加file表单字段,即<input ty

  • java实现文件上传下载和图片压缩代码示例

    分享一个在项目中用的到文件上传下载和对图片的压缩,直接从项目中扒出来的:) 复制代码 代码如下: package com.eabax.plugin.yundada.utils; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.

  • JAVA技术实现上传下载文件到FTP服务器(完整)

    具体详细介绍请看下文: 在使用文件进行交互数据的应用来说,使用FTP服务器是一个很好的选择.本文使用Apache Jakarta Commons Net(commons-net-3.3.jar) 基于FileZilla Server服务器实现FTP服务器上文件的上传/下载/删除等操作. 关于FileZilla Server服务器的详细搭建配置过程,详情请见 FileZilla Server安装配置教程 .之前有朋友说,上传大文件(几百M以上的文件)到FTP服务器时会重现无法重命名的问题,但本人亲

  • Java通过FTP服务器上传下载文件的方法

    对于使用文件进行交换数据的应用来说,使用FTP 服务器是一个很不错的解决方案. 关于FileZilla Server服务器的详细搭建配置过程,详情请见FileZilla Server安装配置教程.之前有朋友说,上传大文件(几百M以上的文件)到FTP服务器时会重现无法重命名的问题,但本人亲测上传2G的文件到FileZilla Server都没有该问题,朋友们可以放心使用该代码. FavFTPUtil.Java package com.favccxx.favsoft.util; import jav

  • JAVA SFTP文件上传、下载及批量下载实例

    1.jsch官方API查看地址(附件为需要的jar) http://www.jcraft.com/jsch/ 2.jsch简介 JSch(Java Secure Channel)是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序. SFTP(Secure File Transfer Protocol)安全文件传送协议.可以为传输文件提供一种安全的加密方法.SFTP 为 SSH的一部份,是一种传输

随机推荐