当前位置:首页 » 文件管理 » spring上传进度

spring上传进度

发布时间: 2022-06-24 10:14:10

‘壹’ springmvc怎么上传文件

springmvc怎么实现文件上传

package com.test.controller;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.test.servlet.NoSupportExtensionException;
import com.test.servlet.State;

@Controller
@RequestMapping(value = "/mvc")
public class UploadController {

/** 日志对象*/
private Log logger = LogFactory.getLog(this.getClass());

private static final long serialVersionUID = 1L;

/** 上传目录名*/
private static final String uploadFolderName = "uploadFiles";

/** 允许上传的扩展名*/
private static final String [] extensionPermit = {"txt", "xls", "zip"};

@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> fileUpload(@RequestParam("file") CommonsMultipartFile file,
HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception{
logger.info("UploadController#fileUpload() start");

//清除上次上传进度信息
String curProjectPath = session.getServletContext().getRealPath("/");
String saveDirectoryPath = curProjectPath + "/" + uploadFolderName;
File saveDirectory = new File(saveDirectoryPath);
logger.debug("Project real path [" + saveDirectory.getAbsolutePath() + "]");

// 判断文件是否存在
if (!file.isEmpty()) {
String fileName = file.getOriginalFilename();
String fileExtension = FilenameUtils.getExtension(fileName);
if(!ArrayUtils.contains(extensionPermit, fileExtension)) {
throw new NoSupportExtensionException("No Support extension.");
}
file.transferTo(new File(saveDirectory, fileName));
}

logger.info("UploadController#fileUpload() end");
return State.OK.toMap();
}

}

‘贰’ 基于springmvc文件上传并显示进度条前台是怎么获取session

前台获取session???现在的html是静态语言不能获取的吧,又不像jsp那样直接request.getSession。并且b端获取session根本没啥意义

‘叁’ SpringBoot超大文件上传如何实现

不管什么技术,超大文件上传(超出一次tcp上限)都是要做分片和合并的,无非是自己做还是找控件的差别。
另外,springboot是后台接收,前端实现是由前端框架负责,比如vue。
以下是Vue+Springboot实现大文件上传的二种方式:
1、利用ElementUI的el-upload
优点:
简单方便,可以实现功能
缺点:
上传速度太慢,没有分片单线程上传1个G的文件即使在局域网也很慢
上传显示的进度条不准确,进度已经100%了,但是还需要等很久在服务端才生成完文
2、利用网络的webuploader
优点:
WebUploader是网上比较推荐的方式,分片上传大文件速度很快。
缺点:
必须依赖 jquery
不能 import 导入,只能在 index.html 里包含。
3. 利用vue-uploader
vue-uploader 是基于vue的uploader组件,缺省就是分片上传。
通过npm安装,基本流程参考github上的说明即可。
上传的基本原理就是前端根据文件大小,按块大小分成很多块,然后多线程同时上传多个块,同时调用服务端的上传接口,服务端会生成很多小块小块的文件。
所有块都上传完之后,前端再调用一个服务端的merge接口,服务端把前面收到的所有块文件按顺序组合成最终的文件。

‘肆’ 如何实现Spring MVC 图片上传时,图片如何代替进度条

不是用图片代替进度条吧,应该可以用个div加点样式,根据进度调整宽度呀。哈哈 个人愚见。

‘伍’ spring文件上传

万变不离其宗,要实现文件的上传需要对应的JAR包:
1、commons-fileupload-1.2.2.jar
2、commons-io-2.0.1.jar

‘陆’ springmvc怎么做上传进度条,前台后台分别怎么写

前台一般传标准的时间格式的字符串到后台,后台接收到时间字符串后用java.lang.util包下的SimpleDateFormat解析成date类型即可。

‘柒’ java多文件上传显示进度条

使用 apache fileupload ,spring MVC jquery1.6x , bootstrap 实现一个带进度条的多文件上传,由于fileupload 的局限,暂不能实现每个上传文件都显示进度条,只能实现一个总的进度条,效果如图:

packagecom.controller;

importjava.util.List;

importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;

importorg.apache.commons.fileupload.FileItemFactory;
importorg.apache.commons.fileupload.ProgressListener;
importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
importorg.apache.commons.fileupload.servlet.ServletFileUpload;
importorg.apache.log4j.Logger;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.servlet.ModelAndView;

@Controller
{
Loggerlog=Logger.getLogger(FileUploadController.class);

/**
*upload上传文件
*@paramrequest
*@paramresponse
*@return
*@throwsException
*/
@RequestMapping(value="/upload.html",method=RequestMethod.POST)
publicModelAndViewupload(HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
finalHttpSessionhs=request.getSession();
ModelAndViewmv=newModelAndView();
booleanisMultipart=ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
returnmv;
}
//Createafactoryfordisk-basedfileitems
FileItemFactoryfactory=newDiskFileItemFactory();

//Createanewfileuploadhandler
ServletFileUploapload=newServletFileUpload(factory);
upload.setProgressListener(newProgressListener(){
publicvoipdate(longpBytesRead,longpContentLength,intpItems){
ProcessInfopri=newProcessInfo();
pri.itemNum=pItems;
pri.readSize=pBytesRead;
pri.totalSize=pContentLength;
pri.show=pBytesRead+"/"+pContentLength+"byte";
pri.rate=Math.round(newFloat(pBytesRead)/newFloat(pContentLength)*100);
hs.setAttribute("proInfo",pri);
}
});
Listitems=upload.parseRequest(request);
//Parsetherequest
//Processtheuploadeditems
//Iteratoriter=items.iterator();
//while(iter.hasNext()){
//FileItemitem=(FileItem)iter.next();
//if(item.isFormField()){
//Stringname=item.getFieldName();
//Stringvalue=item.getString();
//System.out.println("thisiscommonfeild!"+name+"="+value);
//}else{
//System.out.println("thisisfilefeild!");
//StringfieldName=item.getFieldName();
//StringfileName=item.getName();
//StringcontentType=item.getContentType();
//booleanisInMemory=item.isInMemory();
//longsizeInBytes=item.getSize();
//FileuploadedFile=newFile("c://"+fileName);
//item.write(uploadedFile);
//}
//}
returnmv;
}


/**
*process获取进度
*@paramrequest
*@paramresponse
*@return
*@throwsException
*/
@RequestMapping(value="/process.json",method=RequestMethod.GET)
@ResponseBody
publicObjectprocess(HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
return(ProcessInfo)request.getSession().getAttribute("proInfo");
}

classProcessInfo{
publiclongtotalSize=1;
publiclongreadSize=0;
publicStringshow="";
publicintitemNum=0;
publicintrate=0;
}

}

‘捌’ 前端上传文件实时显示进度条和上传速度的工作原理是怎样的

后端的责任。

‘玖’ spring mvc 怎么实现上传文件

springmvc文件上传
1.加入jar包:
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
lperson.java中加属性,实现get ,set方法
private String photoPath;
2.创建WebRoot/upload目录,存放上传的文件

1 <sf:form id="p" action="saveOrUpdate"
2 method="post"
3 modelAttribute="person"
4 enctype="multipart/form-data">
5
6 <sf:hidden path="id"/>
7 name: <sf:input path="name"/><br>
8 age: <sf:input path="age"/><br>
9 photo: <input type="file" name="photo"/><br>

上面第9行文件上传框,不能和实体对象属性同名,类型不同

controller配置

1 12、文件上传功能实现 配置文件上传解析器
2 @RequestMapping(value={"/saveOrUpdate"},method=RequestMethod.POST)
3 public String saveOrUpdate(Person p,
4 @RequestParam("photo") MultipartFile file,
5 HttpServletRequest request
6 ) throws IOException{
7 if(!file.isEmpty()){
8 ServletContext sc = request.getSession().getServletContext();
9 String dir = sc.getRealPath(“/upload”); //设定文件保存的目录
10
11 String filename = file.getOriginalFilename(); //得到上传时的文件名
12 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());
13
14 p.setPhotoPath(“/upload/”+filename); //设置图片所在路径
15
16 System.out.println("upload over. "+ filename);
17 }
18 ps.saveOrUpdate(p);
19 return "redirect:/person/list.action"; //重定向
20 }

3.文件上传功能实现 spring-mvc.xml 配置文件上传解析器

1 <!-- 文件上传解析器 id 必须为multipartResolver -->
2 <bean id="multipartResolver"
3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4 <property name="maxUploadSize" value=“10485760"/>
5 </bean>
6
7 maxUploadSize以字节为单位:10485760 =10M id名称必须这样写

1 映射资源目录
2 <mvc:resources location="/upload/" mapping="/upload/**"/>

随即文件名常用的三种方式:
文件上传功能(增强:防止文件重名覆盖)
fileName = UUID.randomUUID().toString() + extName;
fileName = System.nanoTime() + extName;
fileName = System.currentTimeMillis() + extName;

1 if(!file.isEmpty()){
2 ServletContext sc = request.getSession().getServletContext();
3 String dir = sc.getRealPath("/upload");
4 String filename = file.getOriginalFilename();
5
6
7 long _lTime = System.nanoTime();
8 String _ext = filename.substring(filename.lastIndexOf("."));
9 filename = _lTime + _ext;
10
11 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());
12
13 p.setPhotoPath("/upload/"+filename);
14
15 System.out.println("upload over. "+ filename);
16 }

图片显示 personList.jsp
1 <td><img src="${pageContext.request.contextPath}${p.photoPath}">${p.photoPath}</td>

‘拾’ 如何在spring mvc 里加入监听器,来监听文件上传进度条

一般要用第三方 上传的 软件。有flash支持的那种
否则进度条实现还是比较复杂的
要新建一个线程 不停的查看服务器端已经接收到的文件的大小
然后用这个大小 除以 上传文件的本来size 才能得出一个百分比。

热点内容
微信电脑登录显示服务器错误 发布:2024-04-27 20:58:08 浏览:134
压缩弹簧安装 发布:2024-04-27 20:35:43 浏览:371
淘宝视频无法上传视频 发布:2024-04-27 20:31:27 浏览:643
安卓软件怎么分享 发布:2024-04-27 20:28:26 浏览:669
宽带测速上传 发布:2024-04-27 20:23:22 浏览:174
mysql存储过程ifand 发布:2024-04-27 20:17:12 浏览:252
4位数密码锁怎么开 发布:2024-04-27 20:10:31 浏览:853
倾倒压缩机 发布:2024-04-27 20:00:34 浏览:652
根中根算法 发布:2024-04-27 19:51:44 浏览:749
简易八音盒程序编译 发布:2024-04-27 19:25:07 浏览:862