java中的接口是类吗
357
2023-06-06
spring MVC + bootstrap实现文件上传示例(带进度条)
最近学习了bootstrap,有结合了spring MVC写了个文件上传的示例,留做笔记,废话不多说,直接上代码
监听器类FileUploadProgressListener.java
package com.gpl.web.listener;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;
import com.gpl.web.utils.Progress;
@Component
public class FileUploadProgressListener implements ProgressListener{
private HttpSession session;
public void setSession(HttpSession session){
this.session = session;
Progress status = new Progress();
session.setAttribute("status", status);
}
@Override
public void update(long bytesRead, long contentLength, int items) {
Progress status = (Progress) session.getAttribute("status");
status.setBytesRead(bytesRead);
status.setContentLength(contentLength);
status.setItems(items);
}
}
CustomerMyltipartResolver.java
package com.gpl.web.listener;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
public class CustomMultipartResolver extends CommonsMultipartResolver{
@Autowired
private FileUploadProgressListener progressListener;
public void setFileUploadProgressListener(FileUploadProgressListener progressListener){
this.progressListener = progressListener;
}
public MultipartParsingResult parsingResult(HttpServletRequest request){
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
progressListener.setSession(request.getSession());
fileUpload.setProgressListener(progressListener);
try{
List
return parseFileItems(fileItems, encoding);
}catch(FileUploadBase.SizeLimitExceededException ex){
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
}catch (FileUploadException e) {
throw new MultipartException("异常",e);
}
}
}
进度实体类Progress.java
package com.gpl.web.utils;
public class Progress {
private long bytesRead;
private long contentLength;
private long items;
public long getBytesRead() {
return bytesRead;
}
public void setBytesRead(long bytesRead) {
this.bytesRead = bytesRead;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public long getItems() {
return items;
}
public void setItems(long items) {
this.items = items;
}
@Override
public String toString() {
return "Progress [bytesRead=" + bytesRead + ", contentLength=" + contentLength + ", items=" + items + "]";
}
}
spring配置文件需加入如下bean
controller层实现
/**
* 文件上传
* @param request
* @param response
* @param file
* @throws IOException
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request,HttpServletResponse response,@RequestParam("file") CommonsMultipartFile file)
{
try{
PrintWriter out;
boolean flag = false;
if(file.getSize() > 0){
String path = "/asserts/upload/files/excel/";
String uploadPath = request.getSession().getServletContext().getRealPath(path);
System.out.println(uploadPath);
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadPath,file.getOriginalFilename()));
flag = true;
}
out = response.getWriter();
if(flag == thttp://rue){
out.print("1");
}else{
out.print("2");
}
}catch(Exception e){
e.printStackTrace();
}
}
前端代码
closed="true">
aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"
style="width:0%;">
页面ready加入的js代码
$("#uploadBtn").attr("disabled",false);
$("#uploadBtn").click(function(){
var fileValue = $("#file").val();
if(fileValue == null || fileValue == ""){
layer.msg("请先选择文件");
return;
}
var obj = $("#file");
var photoExt=obj.val().substr(obj.val().lastIndexOf(".")).toLowerCase();//获得文件后缀名
if(photoExt!=".xls" && photoExt!=".xlsx"){
layer.msg("请选择xls或是xlsx格式的文件,不支持其他格式文件");
return false;
}
var fileSize = 0;
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
if (isIE && !obj.files) {
var filePath = obj.val();
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
}else {
fileSize = obj.get(0).files[0].size;
}
fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
if(fileSize > 5000){
layer.msg("文件不能大于5M");
return false;
}
$("#progressBar").width("0%");
$(this).attr("disabled",true);
$("#progressBar").parent().show();
$("#progressBar").parent().addClass("active");
uploadFile();
上传文件js代码
function uploadFile() {
var fileObj = $("#file").get(0).files[0]; // js 获取文件对象
console.info("上传的文件:"+fileObj);
var FileController = "${basePath}/batch/upload"; // 接收上传文件的后台地址
// FormData 对象
var form = new FormData();
// form.append("author", "hooyes"); // 可以增加表单数据
form.append("file", fileObj); // 文件对象
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("post", FileController, true);
xhr.onload = function() {
layer.msg("上传完成");
$("#uploadBtn").attr('disabled', false);
$("#uploadBtn").val("上传");
$("#progressBar").parent().removeClass("active");
$("#progressBar").parent().hide();
};
xhr.upload.addEventListener("progress", progressFunction, false);
xhr.send(form);
}
function progressFunction(evt) {
var progressBar = $("#progressBar");
if (evt.lengthComputable) {
var completePercent = Math.round(evt.loaded / evt.total * 100)+ "%";
progressBar.width(completePercent);
$("#uploadBtn").val("正在上传 " + completePercent);
}
};
效果图
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~