Java实现文件上传的两种方法(uploadify和Spring)
发布时间:2020-05-23 15:27:37 所属栏目:Java 来源:互联网
导读:最近项目中用到的两种文件上传方式做一下总结:一.uploadify:uploadify控件的scripts和styles在这里:图片上传
|
最近项目中用到的两种文件上传方式做一下总结: 一. uploadify: uploadify控件的scripts和styles在这里:图片上传 JSP:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="../jsp/include/taglibs.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Upload</title>
<script src="<c:url value="/scripts/jquery-1.8.3.min.js"/>" type="text/javascript"></script>
<script type="text/javascript" src="<c:url value="/scripts/jquery-admin/jquery-ui.js" />"></script>
<script type="text/javascript" src="<c:url value="/scripts/jquery-admin/component.js" />"></script>
<script type="text/javascript" src="<c:url value="/scripts/jquery-admin/jquery-validate.js" />"></script>
<script type="text/javascript" src="<c:url value="/scripts/jquery-admin/jquery-form.js" />"></script>
<script type="text/javascript"src="<c:url value="/scripts/jquery-admin/init.js" />"></script>
<script type="text/javascript"src="<c:url value="/scripts/jquery-admin/jquery.ui.datepicker-zh-CN.js" />"></script>
<link rel="stylesheet" href="<c:url value='/styles/admin/admin1.css'/>" rel="external nofollow" >
<link href="<c:url value=" rel="external nofollow" rel="external nofollow" /styles/jquery-ui/jquery-ui.css" />" rel="stylesheet" type="text/css" />
<script src="<c:url value="/scripts/jquery-uploadify/jquery.uploadify.min.js"/>" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<c:url value=" rel="external nofollow" rel="external nofollow" /scripts/jquery-uploadify/uploadify.css"/>">
<style type="text/css">
#jidAttachTable {width:400px;font-size:14px;border:1px solid #d3d3d3;border-left-width:0;border-top-width:0;}
#jidAttachTable td{border: 1px solid #d3d3d3;text-align:left;padding:5px;border-right-width:0;border-bottom-width:0;}
#jidAttachTable .i-i-title{width:450px;}
#jidAttachTable .i-i-content{width:100px;}
</style>
<script type="text/javascript">
$(function(){
//视频上传
var uploadVideo = $('#file_upload_video').uploadify({
'buttonText':'上传视频','multi': false,'fileTypeDesc': '请选择wmv视频文件','fileTypeExt': '*.wmv','swf' : '<c:url value="/scripts/jquery-uploadify/uploadify.swf"/>"','uploader' : '<c:url value="/uploadAttach.do"/>','onUploadError': uploadVideoUploadError,'onUploadSuccess':uploadVideoUploadSuccess
});
function uploadVideoUploadError(){
alert("上传视频发生错误");
}
function uploadVideoUploadSuccess(file,data,response){
var strs_ = data.split("@");
var videoName_ = strs_[0];
var videoPath_ = strs_[1];
$("#vidioPreview").val("/upload/" + videoPath_);
}
var arrAttach = new Array();
//将现有的附件加载到临时数组中
var nowAttachIds_ = "${attachs}";
//初始化现有的附件
if(nowAttachIds_ != null && nowAttachIds_ != ""){
var ids_ = nowAttachIds_.split("@") ;
var i = 0;
for( ; i < ids_.length ; i++){
arrAttach.push(ids_[i]);
}
}
//附件上传
var uploadAttach = $('#file_upload_attach').uploadify({
'buttonText':'上传附件','onUploadError': uploadAttachUploadError,'onUploadSuccess':uploadAttachUploadSuccess
});
function uploadAttachUploadError(){
alert("上传过程中发生错误,您可以尝试重复上传一次!")
}
function uploadAttachUploadSuccess(file,response){
var strs_ = data.split("@") ;
var documnetId_ = strs_[0];
var fileName_ = strs_[1];
var attach_ = "<tr class="jsClassDeleteAttachButtonTR"> " +
" <td class='i-i-title'>" + fileName_ + "</td> " +
" <td class='i-i-content'><button class="jsClassDeleteAttachButton" dataAttach="+ documnetId_ +">删除</button></td>" +
" </tr>";
arrAttach.push(documnetId_);
$("#jidAttachTable").append(attach_);
}
$(".jsClassDeleteAttachButton").live("click",function(){
var data_ = $(this).attr("dataAttach");
var i_ = 0;
for(;i_ < arrAttach.length; i_++){
if(data_ == arrAttach[i_]){
arrAttach.splice(i_,1);
break;
}
}
$(this).parent().parent().remove();
//alert(arrAttach)
});
});
var videotag = "";
$(function() {
$("#PreviewDiv").dialog({
title: "视频预览",autoOpen: false,modal: true,resizable: false,position : "center",width: "489px",buttons: {
"关闭": function() {
$("#PreviewDiv").dialog("close");
}
}
});
$( "#PreviewDiv" ).on( "dialogopen",function( event,ui ) {
$("#PreviewDiv").html(videotag);
} );
$( "#PreviewDiv" ).on( "dialogclose",ui ) {
$("#PreviewDiv").html("");
} );
});
var video_root_path = "http://localhost:8080/ProjectTest/";
function openDownloadFrame() {
var _storePreview= video_root_path + $("#vidioPreview").val();
var _embed_head = '<EMBED src="';
var _embed_tail = '" width="450" height="400" type="audio/x-wav" loop="false" autostart="true">' + '</EMBED>';
videotag = _embed_head + _storePreview + _embed_tail;
$("#PreviewDiv").dialog("open");
}
</script>
</head>
<body>
<form:form id="form" name="basedata" modelAttribute="basedata" action="update.do" method="post" >
<div style="height:40px;border:1px solid #ebebeb;padding:10px;">
<div style="width:150px;float:left;">
<input id="file_upload_video" name="file_upload_video" type="file" multiple="true">
</div>
<div style="padding-left:10px;">
<input id="vidioPreview" type="text" name="${bad.attributeStore}" value="${basedata[storeName]}"/>
<input onclick="openDownloadFrame();" type="button" name="button" value="预览">
</div>
</div>
<div id='divContext' style="height:40px;border:1px solid #ebebeb;padding:10px;">
<div style="width:150px;float:left;">
<input id="file_upload_attach" name="file_upload_attach" type="file" multiple="true">
</div>
<div class="i-attachContainer">
<table id="jidAttachTable">
<c:forEach items="${attachList}" var="attach">
<tr class="jsClassDeleteAttachButtonTR">
<td class='i-i-title'>${attach.name}</td>
<td class='i-i-content'>
<button class="jsClassDeleteAttachButton" dataAttach="${attach.id}">删除</button>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<div id="PreviewDiv">
</div>
</form:form>
</body>
</html>
后台Java:
package com.sun.fileUpload;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class upload{
// 附件上传
@RequestMapping("/uploadAttach.do")
public void attachUpload(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) throws IOException {
System.out.println("upload file .... start");
String savePath = request.getSession().getServletContext().getRealPath("/") + "upload";
System.out.println("store path is :" + savePath);
File f1 = new File(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
List<FileItem> fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
ex.printStackTrace();
return;
}
Iterator<FileItem> it = fileList.iterator();
String name = "";
System.out.println("deal the files ... start");
//存储完毕保存进入数据库
//Document document = null;
while (it.hasNext()) {
FileItem item = it.next();
if (!item.isFormField()) {
name = item.getName();
long size = item.getSize();
String type = item.getContentType();
if (name == null || name.trim().equals("")) {
continue;
}
System.out.println("dealing file info:" + "fileName" + name + " size" + size + " type:" + type);
//扩展名格式:
if (name.lastIndexOf(".") >= 0) {
name.substring(name.lastIndexOf("."));
}
//存文件到磁盘指定路径 且存储文件记录存入数据库,如果存储发生故障,数据库记录也会创建失败
/* document = new Document();
document.setFileType(extName);
document.setFullName(name);
document.setDescription(name);
document.setName(name);
document.setUploadDate(new Date());
document = documentManager.saveWithFileStore(document,item,savePath,extName);*/
System.out.println(new Date() + "persist id :" + name);
File saveFile = new File(savePath + "/" + name);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(new Date() + "store file error");
}
}
}
System.out.println("deal the files end");
System.out.println("upload file .... end");
response.getWriter().print(name + "@" + name);
}
}
这里把数据库更新给省略了,有需要可以自己添加。 除上传外,其他实现功能: (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
