如何在Java項目中實現(xiàn)一個文件上傳和下載功能-創(chuàng)新互聯(lián)

如何在Java項目中實現(xiàn)一個文件上傳和下載功能?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

成都創(chuàng)新互聯(lián)自2013年創(chuàng)立以來,是專業(yè)互聯(lián)網(wǎng)技術服務公司,擁有項目成都做網(wǎng)站、網(wǎng)站制作網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元桂陽做網(wǎng)站,已為上家服務,為桂陽各地企業(yè)和個人服務,聯(lián)系電話:13518219792

項目結(jié)構(gòu)如下:


如何在Java項目中實現(xiàn)一個文件上傳和下載功能

主要的是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屬性值
 //請求信息中的內(nèi)容是否是multipart類型
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 //上傳文件的存儲路徑(服務器文件系統(tǒng)上的絕對文件路徑)
 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();
 }
 }
%>

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

效果圖:

如何在Java項目中實現(xiàn)一個文件上傳和下載功能

如何在Java項目中實現(xiàn)一個文件上傳和下載功能

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

@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 : 二進制流數(shù)據(jù)(最常見的文件下載)。
 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
 return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), 
 headers, HttpStatus.CREATED); 
 }
}

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

<bean id="multipartResolver" 
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
 <!-- 上傳文件大小上限,單位為字節(jié)(10MB) -->
 <property name="maxUploadSize"> 
 <value>10485760</value> 
 </property> 
 <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認為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屬性值
 //請求信息中的內(nèi)容是否是multipart類型
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 //上傳文件的存儲路徑(服務器文件系統(tǒng)上的絕對文件路徑)
 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 : 二進制流數(shù)據(jù)(最常見的文件下載)。
 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"> 
 <!-- 上傳文件大小上限,單位為字節(jié)(10MB) -->
 <property name="maxUploadSize"> 
 <value>10485760</value> 
 </property> 
 <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認為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>

關于如何在Java項目中實現(xiàn)一個文件上傳和下載功能問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。

分享名稱:如何在Java項目中實現(xiàn)一個文件上傳和下載功能-創(chuàng)新互聯(lián)
當前URL:http://bm7419.com/article36/hcjsg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、網(wǎng)站制作、網(wǎng)站設計、品牌網(wǎng)站制作、用戶體驗、移動網(wǎng)站建設

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化