一、上传文件

  1、使用 transferTo 上传

@ResponseBody
@RequestMapping(value = "/file/upload")
public ResultModel upload(@RequestParam MultipartFile file, HttpServletRequest request) {
ResultModel resultModel = new ResultModel();
String fileName = file.getOriginalFilename();
String newFileName = IdUtil.uuid() + "_" + fileName;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateFolder = sdf.format(new Date()); //文件后缀名
String fileNameLower = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length()).toLowerCase();//toLowerCase();//小写文件名
String staticFileType = ".jpg,.png,.txt,.doc,.zip,.mp4";//允许上传的类型格式
String uploadPath = "/usr/data/upload"; //服务器上传路径 if(staticFileType.indexOf(fileNameLower) != -1){
long len = file.getSize(); //上传文件大小
if(len <= 20971520) {
if (file.isEmpty()) {
return resultModel;
}
//上传文件 服务器路径 + 当前日期 例如:201900808
String fileUploadPath = uploadPath + "/"+dateFolder + "/";
File f = new File(fileUploadPath);
if(!f.exists()){
f.mkdirs();
}
String filePath = fileUploadPath + newFileName;
File targetFile = new File(filePath);
try {
//将上传的文件写到服务器上指定的文件。
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
//保存文件路径到数据库中
fileAttachService.insert(filePath, fileName);
}else{
resultModel.setStatus(500);
resultModel.setStatuMsg("文件大小不能超过20M!"); //文件大小不能超过20M
return resultModel;
}
}else{
resultModel.setStatus(500);
resultModel.setStatuMsg("文件后缀名不符合规范!"); //文件后缀名不符合规范
return resultModel;
}
return resultModel;
}

  2.使用 org.springframework.util.FileCopyUtils.copy()

import org.springframework.util.FileCopyUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; public class UploadFilesController {
@ResponseBody
@RequestMapping(value = "/file/upload")
public ResultModel upload(@RequestParam MultipartFile file, HttpServletRequest request) {
ResultModel resultModel = new ResultModel();
String fileName = file.getOriginalFilename();
String newFileName = IdUtil.uuid() + "_" + fileName;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateFolder = sdf.format(new Date()); //文件后缀名
String fileNameLower = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length()).toLowerCase();//toLowerCase();//小写文件名
String staticFileType = ".jpg,.png,.txt,.doc,.zip,.mp4";//允许上传的类型格式
String uploadPath = "/usr/data/upload"; //服务器上传路径 if(staticFileType.indexOf(fileNameLower) != -1){
long len = file.getSize(); //上传文件大小
if(len <= 20971520) {
if (file.isEmpty()) {
return resultModel;
}
//上传文件 服务器路径 + 当前日期 例如:201900808
String filePath = uploadPath + "/"+dateFolder + "/" ; File saveFile = new File(filePath,newFileName);
try {
if(!saveFile.exists()){
saveFile.createNewFile();
}
FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
}
catch (IOException e) {
e.printStackTrace();
}
//保存文件路径到数据库中
fileAttachService.insert(filePath, fileName);
}else{
resultModel.setStatus(500);
resultModel.setStatuMsg("文件大小不能超过20M!"); //文件大小不能超过20M
return resultModel;
}
}else{
resultModel.setStatus(500);
resultModel.setStatuMsg("文件后缀名不符合规范!"); //文件后缀名不符合规范
return resultModel;
}
return resultModel;
}
}

二、下载文件

import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.*;
public class UploadFilesController { @RequestMapping(value = "/file/download/{fileId}")
public void download(@PathVariable("fileId") String fileId, HttpServletRequest request, HttpServletResponse response) {
FileAttach fileAttach = fileAttachService.selectById(fileId);
File file = new File(fileAttach.getFilePath()); InputStream in = null;
OutputStream os = null;
try {
//String fileName = URLEncoder.encode(fileAttach.getFileName(), "UTF-8").replaceAll("\\+", "%20");
String fileName = new String(fileAttach.getFileName().getBytes("gb2312"), "ISO8859-1");//解决中文名乱码
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
response.setHeader("Content-Length", ""file.length());//展示下载进度
in = new FileInputStream(file);
os = response.getOutputStream();
IOUtils.copyLarge(in, os);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(os);
}
}
}

  

JAVA 文件的上传下载的更多相关文章

  1. java文件夹上传下载控件分享

    用过浏览器的开发人员都对大文件上传与下载比较困扰,之前遇到了一个需要在JAVA.MyEclipse环境下大文件上传的问题,无奈之下自己开发了一套文件上传控件,在这里分享一下.希望能对你有所帮助. 以下 ...

  2. java文件断点续传上传下载解决方案

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

  3. java文件夹上传下载组件

    核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...

  4. JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

  5. Spring实现文件的上传下载

    背景:之前一直做的是数据库的增删改查工作,对于文件的上传下载比较排斥,今天研究了下具体的实现,发现其实是很简单.此处不仅要实现单文件的上传,还要实现多文件的上传. 单文件的下载知道了,多文件的下载呢? ...

  6. SocketIo+SpringMvc实现文件的上传下载

    SocketIo+SpringMvc实现文件的上传下载 socketIo不仅可以用来做聊天工具,也可以实现局域网(当然你如果有外网也可用外网)内实现文件的上传和下载,下面是代码的效果演示: GIT地址 ...

  7. JAVAWEB之文件的上传下载

    文件上传下载 文件上传: 本篇文章使用的文件上传的例子使用的都是原生技术,servelt+jdbc+fileupload插件,这也是笔者的习惯,当接触到某些从未接触过的东西时,总是喜欢用最原始的东西将 ...

  8. SSM框架之中如何进行文件的上传下载

    SSM框架的整合请看我之前的博客:http://www.cnblogs.com/1314wamm/p/6834266.html 现在我们先看如何编写文件的上传下载:你先看你的pom.xml中是否有文件 ...

  9. 使用Fileupload完成文件的上传下载

    目录 使用Fileupload完成文件的上传下载 为什么需要进行文件上传下载? 引入jar包 文件上传 注意事项 编写一个简单的文件上传jsp页面 编写Servlet Student类用于封装数据,后 ...

随机推荐

  1. Mysql 查询表中某字段的重复值,删除重复值保留id最小的数据

    1 查询重复值 ); 2 删除重复值 -- 创建临时表 ) ); -- 把重复数据放进临时表 INSERT Hb_Student_a SELECT id,studentNumber FROM Hb_S ...

  2. SOCK_SEQPACKE

    The SOCK_SEQPACKET socket type is similar to the SOCK_STREAM type, and is also connection-oriented. ...

  3. 2变量与基本类型之const限定符

    一.const介绍: const对象一旦被创建其值就不能再改变,所以const对象必须初始化.任何试图对const赋值的行为都会引发错误. 二.初始化和const: 对const对象的主要限制就是只能 ...

  4. layui中load具体用法

    遮盖窗体,demo: layer.load(,{ // content: "加载中...", shade: [0.4,'#000'], //0.1透明度的白色背景 time:* } ...

  5. Servlet - Tomcat服务器相关

    1. 服务器 : 服务器其实就是代码编写的一个程序, 可以根据用户发送的请求, 调用执行对应的逻辑代码 2. Tomcat目录结构说明 : \bin : 存放启动和关闭Tomcat的可执行文件 \co ...

  6. JAVA大数——lightoj1024

    要用 System.gc() 清理内存 类必须命名成Main,一些大整数的操作 import java.math.BigInteger; import java.util.Scanner; publi ...

  7. php-fpm 服务

    编译安装PHP的时候已经加入了--enable-fpm 在此基础上启动php-fpm服务 cp /usr/local/php/etc/php-fpm.conf.default /usr/local/p ...

  8. BZOJ 3626: [LNOI2014]LCA(树剖+差分+线段树)

    传送门 解题思路 比较有意思的一道题.首先要把求\(\sum\limits_{i=l}^r dep[lca(i,z)]\)这个公式变一下.就是考虑每一个点的贡献,做出贡献的点一定在\(z\)到根节点的 ...

  9. c实现swap函数陷阱

    swap函数陷阱 使用c实现一个交换两个数的函数,代码很简单: void swap(int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; } 只有3行代码,且 ...

  10. python 测试框架nose

    python测试框架nose nose不是python自带模块,这里我才用pip的方式安装 pip install nose 这样就完成了安装,然后再确认下是否安装成功了,直接打开cmd输入noset ...