File upload function in user management
需求
完成用户文件上传
1:将上传的文件统一放置到upload的文件夹下
2:将每天上传的文件,使用日期格式的文件夹分开,将每个业务的模块放置统一文件夹下
3:上传的文件名要指定唯一,可以使用UUID的方式,也可以使用日期作为文件名
4:封装一个文件上传的方法,该方法可以支持多文件的上传,即支持各种格式文件的上传
5:保存路径path的时候,使用相对路径进行保存,这样便于项目的可移植性
实现步骤
1.在util包下封装一个方法
public class FileUtils { /** * @Name: fileUploadReturnPath * @Description: 文件上传,返回panth路径 * @Parameters: file:上传文件 * fileName:上传文件名 * model:模块名称 * @Return: String:返回上传路径 * 1:完成文件上传的要求 1:将上传的文件统一放置到upload的文件夹下 2:将每天上传的文件,使用日期格式的文件夹分开,将每个业务的模块放置统一文件夹下 3:上传的文件名要指定唯一,可以使用UUID的方式,也可以使用日期作为文件名 4:封装一个文件上传的方法,该方法可以支持多文件的上传,即支持各种格式文件的上传 5:保存路径path的时候,使用相对路径进行保存,这样便于项目的可移植性*/public static String fileUploadReturnPath(File file, String fileName, String model) {//1.获取upload文件夹路径String basePath = ServletActionContext.getServletContext().getRealPath("/upload");//2.获取日期格式的文件夹(格式yyyy/MM/dd/)String datePath=DateUtils.dateToStringByFile(new Date());//3.全路径格式(例如:upload\2017\7\8\用户管理)String filePath=basePath+datePath+model;//4.判断该文件夹是否存在,若不存在,创建File dateFile = new File(filePath);if(!dateFile.exists()){ dateFile.mkdirs(); }//5.指定对应文件名//获取文件名后缀String suffix = fileName.substring(fileName.lastIndexOf("."));//设置文件名为uuidString uuidFileName = UUID.randomUUID().toString()+suffix;//目标文件File destFile = new File(dateFile,uuidFileName);//上传文件 file.renameTo(destFile);return "/upload"+datePath+model+"/"+uuidFileName; } }
2.jsp页面的表单要求
当导入struts2的jar包时,struts2会默认支持使用fileupload工具上传文件
设置表单属性: enctype=multipart/form-data 表单类型
method=post 提交方式
name=uploads 文件域名称
<form name="Form1"action="${pageContext.request.contextPath }/system/elecUserAction_save.do"method="post" enctype="multipart/form-data"><s:file name="uploads" id="uploads" cssStyle="width:450px;"></s:file> *</form>
3.VO对象中添加非持久化javabean属性
//上传文件private File[] uploads;//上传文件名,该变量的定义必须是上传表单file字段name属性值+FileNameprivate String[] uploadsFileName;//上传文件类型,该变量的定义必须是上传表单file字段name属性值+ContentTypeprivate String[] uploadsContentType; public File[] getUploads() {return uploads; }public void setUploads(File[] uploads) {this.uploads = uploads; }public String[] getUploadsFileName() {return uploadsFileName; }public void setUploadsFileName(String[] uploadFileName) {this.uploadsFileName = uploadFileName; }public String[] getUploadsContentType() {return uploadsContentType; }public void setUploadsContentType(String[] uploadContentType) {this.uploadsContentType = uploadContentType; }
4.Service中添加方法
在用户service实现类中添加附件保存的方法saveUserFile(),并在上篇讲到的saveUser()方法中进行调用
/** * 遍历多个附件,组织附件的PO对象,完成文件上传,保存用户的附件(多条数据),建立附件表和用户表的关联关系 * @param elecUser */private void saveUserFiles(ElecUser elecUser) { Date date = new Date();//获取上传的文件File[] files = elecUser.getUploads();//获取文件名String[] fileNames = elecUser.getUploadsFileName();//获取文件类型String[] contentType = elecUser.getUploadsContentType();//遍历if(files!=null&&files.length>0){for(int i=0;i<files.length;i++){//组织PO对象ElecUserFile elecUserFile = new ElecUserFile(); elecUserFile.setFileName(fileNames[i]); elecUserFile.setProgressTime(date);//将文件上传,同时返回路径pathString fileURL=FileUtils.fileUploadReturnPath(files[i],fileNames[i],"用户管理"); elecUserFile.setFileURL(fileURL); elecUserFile.setElecUser(elecUser);//重要:与用户建立关联关系,如果不建立,外键为null//保存附件 elecUserFileDao.save(elecUserFile); } } }
5.struts2上传文件大小限制
struts2默认可以上传的文件最大限制是2M,如果上传文件大小超过2M,控制台错误如下:
org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (77817949) exceeds the configured maximum (2097152)
该异常信息是common-fileupload组件输出的,而非是Struts2框架
解决办法:在struts.xml中设置上传组件的文件大小限制
<!-- 设置最大上传的大小是80M --><constant name="struts.multipart.maxSize" value="83886080"></constant>
The above is the detailed content of File upload function in user management. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

According to news on April 3, Taipower’s upcoming M50 Mini tablet computer is a device with rich functions and powerful performance. This new 8-inch small tablet is equipped with an 8.7-inch IPS screen, providing users with an excellent visual experience. Its metal body design is not only beautiful but also enhances the durability of the device. In terms of performance, the M50Mini is equipped with the Unisoc T606 eight-core processor, which has two A75 cores and six A55 cores, ensuring a smooth and efficient running experience. At the same time, the tablet is also equipped with a 6GB+128GB storage solution and supports 8GB memory expansion, which meets users’ needs for storage and multi-tasking. In terms of battery life, M50Mini is equipped with a 5000mAh battery and supports Ty

At work, ppt is an office software often used by professionals. A complete ppt must have a good ending page. Different professional requirements give different ppt production characteristics. Regarding the production of the end page, how can we design it more attractively? Let’s take a look at how to design the end page of ppt! The design of the ppt end page can be adjusted in terms of text and animation, and you can choose a simple or dazzling style according to your needs. Next, we will focus on how to use innovative expression methods to create a ppt end page that meets the requirements. So let’s start today’s tutorial. 1. For the production of the end page, any text in the picture can be used. The important thing about the end page is that it means that my presentation is over. 2. In addition to these words,
