分享

一文教你实现java中的文件上传下载

 LRyab博客网 2021-08-17
大家好,我是小编LRyab,公众号LRyab博客网,LRyab博客网是分享一些个人成长、思考方向、个人感悟、职业规划,博客涵盖java技术 vue. html. css.前端技术spring全家桶. linux运维技术在365天把你打造出来一个全栈工程师!

点击下方卡片关注公众号,每天分享一篇技术干货!

 引言:圈子大了什么鸟都有,刷到一个广告,加微信收费需求,前50名9.9扫码支付,支付完成推送会员名片,朋友圈全是价值精华,哦,原来这也是一个赚钱的点子,万物皆有需求,万物皆有价值,这条广告被我看到了,下次准备搞个java学习交流群,里面全是我这么多年工作中遇到的技术难点以及解决方案还有java学习路线。最主要的是我可以帮你搞定简历、课程设计、电商项目实战开发指导的需求。咱也不知道有没有人愿意付费,从今天起我准备我的人生就做2件事:从生活的问题出发,主动学习,并把学习的成功用于解决生活的问题,第二件事还没想好,想好再告诉大家。

  1为什么写java中的文件上传下载解决方案

     自从参加工作之后,我就存在一个问题,很多代码写了几百遍了,下次再想用的时候总是找不到,现在我每次开发完的功能都记录到博客上,特别是今天这篇java文件上传与下载功能特别值得记下来,方便下次使用。

  2java中的文件上传下载技术大纲

     看文章之前,还是老样子,请先看下面这张技术大纲图,大概了解这里面涉及到的技术与流程,坚持按照大纲看完文章你的思路会更清晰

3java中的文件上传下载技术解决方案

3.1案例展示

  该功能前端界面支持,文件拖拽,和点击浏览进行选择文件上传至java后台服务器的数据目录中。

3.2前端HTML代码添加一个File组件

核心组件代码为:<input type="file" style="display:none" c1aaa="ignore-inlina-attach" id="attach-file-id" multiple=""
      name="fileAttachment" remuired="" onchange="displayFiles();">

3.3JS为HTML文档添加拖拽监听事件

JS元素中的:drop事件

3.4AJAX进行FormData文件上传

核心代码:FormData数据格式

var formData=new FormData();
var file=x.files[i];
formData.append('file',file);

3.5后台spring boot 接口 实现

需要注意:使用(@RequestParam(name = "file")MultipartFile file接收File类型的参数。

                  前端上传文件数据需要持久化至数据库。

                  最终文件上传需要留下记录所以需要插入审计日志。

@RequestMapping("/rest")
public class UploadRestApI {
private AttachmentFile attachmentFile;
@Autowired
private AttachmentHelper attachmentHelper;
@RequestMapping(value = "/uploadAttachment" ,method = RequestMethod.POST)
@ResponseBody
@CrossOrigin
public String uploadAttachment(@RequestParam(name = "file")MultipartFile file,@RequestParam("fileName") String fileNmae){

System.out.println("附件上传程序开始");
//1构建附件信息至数据库//1 网关.png image/png 附件ID 附件名称 附件类型

//2持久化文件至磁盘目录
attachmentHelper.createAttachment(UUID.randomUUID().toString(),attachmentFile);
/****
*3 插入审计日志
* 什么人在什么时间段做了什么
*/
//删除服务器附件测试
//attachmentHelper.removeFile(attachmentId);

return "sucess";
}

3.6java中IO 流文件上传实现工具类技巧

/***
附件上传工具类
*/
@Component
public class AttachmentHelper {
private static final Logger log = LoggerFactory.getLogger(AttachmentHelper.class);
private static final String UPLOAD_ATTACHMENT_DIR = "/attachments";
/***
输入流
输出到磁盘文件中
@param attachmentId
@param attachmentFile
*/
public void createAttachment(String attachmentId, AttachmentFile attachmentFile) {
log.debug("Creating attachment in filesystem:" + attachmentId);
File f = new File(getSystemDataDirectory(), UPLOAD_ATTACHMENT_DIR);
if (!f.exists()) {
boolean success = f.mkdirs();
if (!success) {
log.error("unable to create attachement directory in" + getSystemDataDirectory());
log.error("Attachment creation failed");
return;
}
}
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(f, attachmentId.toString())));
InputStream inputStream = null;
if (attachmentFile.getFile() != null) {
inputStream = new FileInputStream(attachmentFile.getFile());
} catch (FileNotFoundException e) {
log.debug(e.getMessage(), e);
log.error("Unable to create file,attachment creation failed");
} catch (IOException e) {
}
}
} else {

inputStream = attachmentFile.getInputFileStream();
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
try {
int inputData;
while ((inputData = bufferedInputStream.read()) != -1) {
bos.write(inputData);
}
} finally {
if (attachmentFile.getFile() != null) {
if (inputStream != null) {
inputStream.close();
}
if (bufferedInputStream != null) {
bufferedInputStream.close();
}
}
if (bos != null) {
bos.close();
}

}
log.debug(e.getMessage(), e);
log.error("Error writiong file content ,attachment creation failed");
获取磁盘文件输入流内容

@param attachmentId
@return
*/
public BufferedInputStream getFileContent(Integer attachmentId) {
log.debug("Reading the file content with attachementId:" + attachmentId);
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(getSystemDataDirectory() + UPLOAD_ATTACHMENT_DIR + attachmentId.toString())));
return bis;
} catch (FileNotFoundException e) {
}

@param attachementId
*/
public void removeFile(Integer attachementId) {
log.debug("Removing file fromm filesystem with ttachmentId:" + attachementId);
//根据文件名称删除
File attachmentFile = new File(getSystemDataDirectory() + UPLOAD_ATTACHMENT_DIR + attachementId.toString());
if (attachmentFile.exists()) {
boolean result = attachmentFile.delete();
if (result) {
log.debug("File successfully deleted!");
} else {
log.warn("Failed to delete file with attachmentId" + attachementId);
}
}

}
/**
获取应用系统数据目录

@return
*/
private File getSystemDataDirectory() {
//可设置为Linux或者windows系统磁盘目录,目前设置为常量
File rootDir = new File("D:\");
return rootDir;
}

}

3.7文件实体类

public class AttachmentFile {
private String name;

private String mimeType;

private File file;

private InputStream inputFileStream;
public AttachmentFile(){

}
public AttachmentFile(String name, String mimeType, File file) {
this.name = name;
this.mimeType = mimeType;
this.file = file;
}

public AttachmentFile(String name, String mimeType, InputStream inputFileStream) {
this.name = name;
this.mimeType = mimeType;
this.inputFileStream = inputFileStream;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getMimeType() {
return mimeType;
}

public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}

public File getFile() {
return file;
}

public void setFile(File file) {
this.file = file;
}

public InputStream getInputFileStream() {
return inputFileStream;
}

public void setInputFileStream(InputStream inputFileStream) {
this.inputFileStream = inputFileStream;
}
}

4结束语

   最近时间有点紧,各种指导方案,各种问题,有点不知所措,忙过头了不是啥好事,一件事做到极致才是专家,足够专注做一件事,才牛逼!过2天给大家更新价值9999的面试宝典,以前都是收费的,现在决定把收费的价值全放出来。

5个人说明

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多