欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實(shí)現(xiàn)上傳和下載功能(支持多個(gè)文件同時(shí)上傳)

 更新時(shí)間:2020年12月13日 10:10:06   作者:岡崎渚  
這篇文章主要介紹了Java實(shí)現(xiàn)上傳和下載功能,支持多個(gè)文件同時(shí)上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

文件上傳一直是Web項(xiàng)目中必不可少的一項(xiàng)功能。

項(xiàng)目結(jié)構(gòu)如下:(這是我之前創(chuàng)建的SSM整合的框架項(xiàng)目,在這上面添加文件上傳與下載)

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

1.先編寫(xiě)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.編寫(xiě)doupload.jsp

<%
 request.setCharacterEncoding("utf-8");
 String uploadFileName = ""; //上傳的文件名
 String fieldName = ""; //表單字段元素的name屬性值
 //請(qǐng)求信息中的內(nèi)容是否是multipart類(lèi)型
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 //上傳文件的存儲(chǔ)路徑(服務(wù)器文件系統(tǒng)上的絕對(duì)文件路徑)
 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()) { //依次處理每個(gè)文件
 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();
 }
 }
%>

該頁(yè)面主要是內(nèi)容是,通過(guò)解析request,并設(shè)置上傳路徑,創(chuàng)建一個(gè)迭代器,先進(jìn)行判空,再通過(guò)循環(huán)來(lái)實(shí)現(xiàn)多個(gè)文件的上傳,再輸出文件信息的同時(shí)打印文件下載路徑。

效果圖:

3.編寫(xiě)FilterController實(shí)現(xiàn)文件下載的功能(相對(duì)上傳比較簡(jiǎn)單):

@Controller
public class FileUploadController {
 @RequestMapping(value="/download")
 public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception { 
 //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 
 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(); 
 //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 
 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
 //通知瀏覽器以attachment(下載方式)打開(kāi)圖片
 headers.setContentDispositionFormData("Content-Disposition", downloadFielName); 
 //application/octet-stream : 二進(jìn)制流數(shù)據(jù)(最常見(jiàn)的文件下載)。
 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
 return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), 
 headers, HttpStatus.CREATED); 
 }
}

4.實(shí)現(xiàn)上傳文件的功能還需要在springmvc中配置bean:

<bean id="multipartResolver" 
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
 <!-- 上傳文件大小上限,單位為字節(jié)(10MB) -->
 <property name="maxUploadSize"> 
 <value>10485760</value> 
 </property> 
 <!-- 請(qǐng)求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為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>上傳處理頁(yè)面</title>
</head>
<body>
<%
 request.setCharacterEncoding("utf-8");
 String uploadFileName = ""; //上傳的文件名
 String fieldName = ""; //表單字段元素的name屬性值
 //請(qǐng)求信息中的內(nèi)容是否是multipart類(lèi)型
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 //上傳文件的存儲(chǔ)路徑(服務(wù)器文件系統(tǒng)上的絕對(duì)文件路徑)
 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()) { //依次處理每個(gè)文件
 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 { 
 //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 
 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(); 
 //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 
 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
 //通知瀏覽器以attachment(下載方式)打開(kāi)圖片
 headers.setContentDispositionFormData("Content-Disposition", downloadFielName); 
 //application/octet-stream : 二進(jìn)制流數(shù)據(jù)(最常見(jiàn)的文件下載)。
 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">
 <!-- 一個(gè)用于自動(dòng)配置注解的注解配置 -->
 <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"> 
 <!-- 上傳文件大小上限,單位為字節(jié)(10MB) -->
 <property name="maxUploadSize"> 
 <value>10485760</value> 
 </property> 
 <!-- 請(qǐng)求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為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>
 <!-- 初始化參數(shù) -->
 <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>

以上便為文件上傳和下載的全部代碼,博主親測(cè)過(guò),沒(méi)有問(wèn)題。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論