注意先导入jar包
单文件上传
且
必须使用enctype进行分装,表示将表单按照二进制的方式提交。即所有的操作表单此时不再是分别提交,而是将所有内容都按照二进制的方式提交。
Jsp页面
Servlet页面:
//设置上传路径
String fliePath=getServletContext().getRealPath("/")+"upload";
System.out.println(fliePath);
File file=new File(fliePath);
//判断路径是否存在
if(!file.exists()){
* mkdirs:这个方法可以在不知道偶没有父类文件夹的情况下,创建文件夹
* mkdir:必须在有父类的文件夹下创建文件
file.mkdirs();
//实例化上传组件
SmartUpload su=new SmartUpload();
//初始化
su.initialize(getServletConfig(),request,response);
//设置上传文件对象大小
su.setMaxFileSize(1024*1024*10);
//设置所有文件大小
su.setTotalMaxFileSize(1024*1024*100);
//设置允许上传文件类型
su.setAllowedFilesList("txt,jpg,gif,png");
String result = "上传成功!";
try {
//设置禁止上传的文件类型
su.setDeniedFilesList("rar,jsp,js");
//上传文件
try {
su.upload();
} catch (SmartUploadException e) {
e.printStackTrace();
//保存文件
try {
su.save(fliePath);
} catch (SmartUploadException e) {
e.printStackTrace();
//获取上传的文件
com.jspsmart.upload.File tempFile = su.getFiles().getFile(0);
//获取上传文件的表单当中file属性的name值
tempFile.getFieldName();
System.out.println("---"+tempFile.getFieldName());
//获取上传的文件名
tempFile.getFileName();
System.out.println("文件名"+tempFile.getFileName());
//获取上传文件的大小
tempFile.getSize();
System.out.println("文件大小"+tempFile.getSize());
//获取上传文件的后缀名
tempFile.getFileExt();
System.out.println("文件的后缀名"+tempFile.getFileExt());
//获取上传文件的上传路径
tempFile.getFilePathName();
System.out.println("文件的全名 "+tempFile.getFilePathName());
} catch (SQLException e) {
result="上传失败";
e.printStackTrace();
多文件上传与单文件上传差不多只要改动前台代码就行了
注:上传多少个就加多少个file字段
下载:
Jsp页面:
1.jpg
注意:下载的value值应该与上传的文件名一致否则会报错
Servlet页面:
//获取fileName的值
String fileName=request.getParameter("fileName");
//实例化SmartUpload对象
SmartUpload su=new SmartUpload();
su.initialize(getServletConfig(), request, response);
su.setContentDisposition(null);
try {
su.downloadFile("/file/"+fileName);
} catch (SmartUploadException e) {
e.printStackTrace();
多文件下载:
Jsp页面
1.jpg 2.jpg
3.jpg
Servlet页面:
String name=request.getParameter("fileName ");
//将文件打包成压缩包格式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Dispositon", "attachment;filename=test.zip");
//设置下载路径
SmartUpload su=new SmartUpload();
request.getParameter("name");
String filePath=getServletContext()
.getRealPath("/")+"file/";
String file []=request.
getParameterValues("fileName");
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
for(String fileNumber:file){
File f=new File(filePath+file);
zos.putNextEntry(new ZipEntry(fileNumber));
FileInputStream fis = new FileInputStream(f);
byte [] b=new byte[1024];
int n=0;
while((n=fis.read(b))!=-1){
zos.write(b, 0,n);
//清空缓存区
zos.flush();
//释放资源
fis.close();
zos.setComment("描述信息");
zos.flush(); zos.close();
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.