java 下载项目中的文件_如何在Java项目中实现一个文件上传和下载功能

本文详细介绍了如何在Java项目中实现文件上传和下载功能,包括编写up.jsp、doupload.jsp,以及使用FileUploadController进行文件下载。通过ServletFileUpload解析请求,将文件保存到服务器,并提供下载链接。同时展示了Spring MVC配置中处理文件上传的部分。
摘要由CSDN通过智能技术生成

如何在Java项目中实现一个文件上传和下载功能

发布时间:2020-12-14 14:26:13

来源:亿速云

阅读:84

作者:Leah

如何在Java项目中实现一个文件上传和下载功能?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

项目结构如下:

a31c544b4256d1ba906de2317fdecb7c.png

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

1.先编写up.jsp

上传者:

选择文件:

选择文件:

以上便是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 items = upload.parseRequest(request);

Iterator 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")+"上传了文件。
");

}

}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下载链接:"+""+uploadFileName+"");

out.print("
");

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

%>

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

效果图:

6e7233a87440b3a42f974b36fed46a71.png

d774998066f4a3d26043974f5085ad8e.png

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

public class FileUploadController {

@RequestMapping(value="/download")

public ResponseEntity 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(FileUtils.readFileToByteArray(file),

headers, HttpStatus.CREATED);

}

}

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

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

10485760

UTF-8

完整代码如下:

up.jsp

HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

File控件

上传者:

选择文件:

选择文件:

doupload.jsp

HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

上传处理页面

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 items = upload.parseRequest(request);

Iterator 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")+"上传了文件。
");

}

}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下载链接:"+""+uploadFileName+"");

out.print("
");

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

%>

FileUploadController.javapackage 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 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(FileUtils.readFileToByteArray(file),

headers, HttpStatus.CREATED);

}

}

SpringMVC.xml(仅供参考,有的地方不可以照搬)<?xml  version="1.0" encoding="UTF-8"?>

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">

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

10485760

UTF-8

web.xml(仅供参考,有的地方不可以照搬)<?xml  version="1.0" encoding="UTF-8"?>

Student

index.html

index.htm

index.jsp

default.html

default.htm

default.jsp

springmvc

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:springmvc.xml

1

springmvc

*.action

contextConfigLocation

classpath:spring/applicationContext-*.xml

org.springframework.web.context.ContextLoaderListener

关于如何在Java项目中实现一个文件上传和下载功能问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值