一 在Head中加入
<script src= /lib/js/ajaxfileupload js type=text/javascript></script><script src= /lib/js/ligerui expand js type=text/javascript></script>
二 Html中的Div代码
<div id="AppendBill_Div" ><% 上传 单 %><table ><tr ><td >图标: </td><td><input type=file id="fileupload" name=fileupload/></td></tr></table></div>
三 Js中 写的是关键部分 会LigerUI的朋友 你懂得
grid中添加项【存地址字段】 { display: "扫描件" name: "AppendBillPath" width: type: "text" align: "left" } Form可添加项【存地址和d出选择框】
{ name: "AppendBillPath " type: "hidden" } // 上传 【 】 { display: "扫描件" name: "AppendBillPath" boboxName: "AppendBillPath " newline: true labelWidth: width: space: type: "select" options: {}} // 上传 【 】 $ ligerui get("AppendBillPath ") set( onBeforeOpen f_selectAppendBillPath_ ) // 【扫描件】 // 上传 【 】 事件
// #region ======================================= 【上传扫描件窗口】 // 上传 【 】
var AppendBillPathDetail = nullfunction f_selectAppendBillPath_ () { var imageurl = $("#AppendBill") val()var AppendBill_Id = $("#AppendBill") val()// 单号 if (imageurl length == ) { LG showError("您没有输入单号 请输入随单号!")return}
if (AppendBillPathDetail) { AppendBillPathDetail show()
} else {
AppendBillPathDetail = $ ligerDialog open({ target: $("#AppendBill_Div") title: 添加图标 width: height: top: left: // d出窗口大小 buttons: [ { text: 上传 onclick: function () { AppendBillPath_save()} } { text: 取消 onclick: function () { AppendBillPathDetail hide()} } ] })} }
function AppendBillPath_save() {
var imgurl = $("#fileupload") val()// var filehelpcode = $("#filehelpcode") val()
var extend = imgurl substring(imgurl lastIndexOf(" ") imgurl length)extend = extend toLowerCase()if (extend == " jpg" || extend == " jpeg" || extend == " png" || extend == " gif" || extend == " bmp") { } else {
LG showError("请上传jpg jpep png gif bmp格式的图片文件")
return} var imageurl = $("#AppendBill") val()// extend alert(imageurl)
$ ajaxFileUpload({ url: " /handle/ImageUpload aspx?imageurl=" + imageurl // 上传 【 】 aspx文件 secureuri: false fileElementId: "fileupload" //Input file id
dataType: "text" success: function (data status) {
// // 保存路径
// $("#AppendBillPath ") val(Data)LG tip(data)f_reload()} error: function (data status e) { LG showError(data)
} })
}
// #endregion 四 后台cs 写一句关键的 可以返回参数 前台提示
lishixinzhi/Article/program/Java/JSP/201311/20623/* jQuery实现文件上传,参考例子如下:
package com.kinth.hddpt.file.action
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.ArrayList
import java.util.Calendar
import java.util.Enumeration
import java.util.Hashtable
import java.util.List
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import net.sf.json.JSONArray
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.struts.action.ActionForm
import org.apache.struts.action.ActionForward
import org.apache.struts.action.ActionMapping
import org.apache.struts.upload.FormFile
import org.hibernate.criterion.MatchMode
import org.hibernate.criterion.Order
import org.hibernate.criterion.Restrictions
import com.gdcn.bpaf.common.base.search.MyCriteria
import com.gdcn.bpaf.common.base.search.MyCriteriaFactory
import com.gdcn.bpaf.common.base.service.BaseService
import com.gdcn.bpaf.common.helper.PagerList
import com.gdcn.bpaf.common.helper.WebHelper
import com.gdcn.bpaf.common.taglib.SplitPage
import com.gdcn.bpaf.security.model.LogonVO
import com.gdcn.components.appauth.common.helper.DictionaryHelper
import com.kinth.common.base.action.BaseAction
import com.kinth.hddpt.file.action.form.FileCatalogForm
import com.kinth.hddpt.file.model.FileCatalog
import com.kinth.hddpt.file.service.FileCatalogService
import com.kinth.hddpt.file.util.MyZTreeNode
/**
* <p>
* description: “文件上传的Struts层请求处理类”
* </p>
* @date : 2013-1-14
*/
public class FileCatalogAction extends BaseAction<FileCatalog> {
@SuppressWarnings("unused")
private static Log log = LogFactory.getLog(FileCatalogAction.class) // 日志记录
private FileCatalogService fileCatalogService
// 删除记录的同时删除相应文件
public ActionForward fileDelete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String[] id = request.getParameterValues("resourceId")
if (id != null && id[0].contains(",")) {
id = id[0].split(",")
}
String[] fileUrls = new String[id.length]
for (int j = 0 j < id.length j++) {
fileUrls[j] = fileCatalogService.findObject(id[j]).getFileUrl()
if (!isEmpty(fileUrls[j])) {
// 如果该文件夹不存在则创建一个uptext文件夹
File fileup = new File(fileUrls[j])
if (fileup.exists() || fileup != null) {
fileup.delete()
}
}
fileCatalogService.deleteObject(id[j])
}
setAllActionInfos(request)
return list(mapping, form, request, response)
}
@Override
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id = request.getParameter("resourceId")
Boolean fileFlag = Boolean.valueOf(request.getParameter("fileFlag"))
if(fileFlag != null && fileFlag == true){
return super.save(mapping, form, request, response)
}else{
String fileUrl = this.fileUpload(form, request, id, fileFlag)
response.setContentType("text/html")
response.setCharacterEncoding("GBK")
response.setHeader("Charset", "GBK")
response.setHeader("Cache-Control", "no-cache")
response.getWriter().write(fileUrl)
response.getWriter().flush()
}
return null
}
@SuppressWarnings("unchecked")
public String fileUpload(ActionForm form,HttpServletRequest request,String id,Boolean fileFlag) throws FileNotFoundException, IOException{
request.setCharacterEncoding("GBK")
String basePath = getServlet().getServletConfig().getServletContext().getRealPath("")+"/"
String filePath = "uploads/" // 获取项目根路径
/*注释部分对应jquery upload uploadify插件的后台代码,只是还存在编码问题,默认为utf-8
String savePath = getServlet().getServletConfig().getServletContext().getRealPath("") // 获取项目根路径
savePath = savePath + "\\uploads\\"
//读取上传来的文件信息
Hashtable<String, FormFile> fileHashtable = form.getMultipartRequestHandler().getFileElements()
Enumeration<String> enumeration = fileHashtable.keys()
enumeration.hasMoreElements()
String key = (String) enumeration.nextElement()
FormFile formFile = (FormFile)fileHashtable.get(key)
String filename = formFile.getFileName().trim() //文件名
filename = new EncodeChange().changeCode(filename)
String filetype = filename.substring(filename.lastIndexOf(".") + 1)//文件类型
savePath = savePath+filetype+"\\"
System.out.println("path:"+savePath)
String realPath = savePath + filename //真实文件路径
//如果该文件夹不存在则创建一个文件夹
File fileup = new File(savePath)
if(!fileup.exists()||fileup==null){
fileup.mkdirs()
}
if (!filename.equals("")) {
// 在这里上传文件
InputStream is = formFile.getInputStream()
OutputStream os = new FileOutputStream(realPath)
int bytesRead = 0
byte[] buffer = new byte[8192]
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead)
}
os.close()
is.close()
//如果是修改 *** 作,则删除原来的文件
String id = request.getParameter("resourceId")
if (!isEmpty(id)) {
FileCatalog fileCatalog = fileCatalogService.findObject(id)
String fileUrl = fileCatalog.getFileUrl()
if (!isEmpty(fileUrl)) {
File filedel = new File(fileUrl)
if(filedel.exists()||filedel!=null){
filedel.delete()
}
}
request.setAttribute("entity", fileCatalog)
}
response.getWriter().print(realPath)// 向页面端返回结果信息
}*/
// 读取上传来的文件信息
Hashtable<String, FormFile> fileHashtable = form.getMultipartRequestHandler().getFileElements()
Enumeration<String> enumeration = fileHashtable.keys()
enumeration.hasMoreElements()
String key = (String) enumeration.nextElement()
FormFile formFile = (FormFile) fileHashtable.get(key)
String filename = formFile.getFileName().trim() // 文件名
String filetype = filename.substring(filename.lastIndexOf(".") + 1)// 文件类型
Integer fileSize = formFile.getFileSize()
filePath += Calendar.getInstance().get(Calendar.YEAR)+"/"+filetype+"/"
String realPath = basePath+filePath+filename // 真实文件路径
if (!filename.equals("")) {
// 如果是修改 *** 作,则删除原来的文件
if (!isEmpty(id)) {
FileCatalog fileCatalog = fileCatalogService.findObject(id)
String fileUrl = fileCatalog.getFileUrl()
if (!isEmpty(fileUrl)) {
fileUrl = basePath + fileUrl
File filedel = new File(fileUrl)
if (filedel.exists() || filedel != null) {
filedel.delete()
}
}
request.setAttribute("entity", fileCatalog)
}
// 如果该文件夹不存在则创建一个文件夹
File fileup = new File(basePath+filePath)
if (!fileup.exists() || fileup == null) {
fileup.mkdirs()
}
// 在这里上传文件
InputStream is = formFile.getInputStream()
OutputStream os = new FileOutputStream(realPath)
int bytesRead = 0
byte[] buffer = new byte[8192]
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead)
}
os.close()
is.close()
}
filePath += filename
String result = "{\"fileName\":\""+filename+"\",\"fileType\":\""+filetype+"\",\"fileSize\":"+fileSize+",\"fileUrl\":\""+filePath+"\"}"
return result
}
public FileCatalogService getFileCatalogService() {
return fileCatalogService
}
public void setFileCatalogService(FileCatalogService fileCatalogService) {
this.fileCatalogService = fileCatalogService
}
}
//js$(function () {
//文件上传地址
//var url = 'http://localhost/index.php/upload/do_upload'
var url = 'http://localhost/index.php/uploadwe'
//初始化,主要是设置上传参数,以及事件处理方法(回调函数)
$('#fileupload').fileupload({
autoUpload: true,//是否自动上传
//url: url,//上传地址
dataType: 'json',
done: function (e, data) {//设置文件上传完毕事件的回调函数
//$.each(data.result.files, function (index, file) {
$("#myimg").attr({src:data.result.imgurl})
$("#myimg").css({width:"290px",height:"218px"})
//alert(data.result)
},
progressall: function (e, data) {//设置上传进度事件的回调函数
var progress = parseInt(data.loaded / data.total * 5, 10)
$('#progress .bar').css(
'width',
progress + '%'
)
}
})
})
//上传至服务后,服务器返回json数据--上传图片的地址。
//html
<label for="text">上传图片</label>
<input id="fileupload" type="file" name="files" data-url="<span style="color:#ff6666">jquery_save_img</span>" multiple>
//data-url为上传至服务器端的处理接口/地址,可替换js中的url
//服务器端
function jquery_save_img()
{
$arrType=array('image/jpg','image/gif','image/png','image/bmp','image/pjpeg','image/jpeg')
$max_size='500000000000' // 最大文件限制(单位:byte)
$upfile='./uploads' //图片目录路径
$file=$_FILES['files']
/*
echo 'filename:'.$file['tmp_name'].'<br />'
echo 'size:'.$file['size'].'<br />'
echo 'type:'.$file['type'].'<br />'
echo 'name:'.$file['name'].'<br />'
*/
if($_SERVER['REQUEST_METHOD']=='POST'){ //判断提交方式是否为POST
if(!is_uploaded_file($file['tmp_name'])){ //判断上传文件是否存在
echo "<font color='#FF0000'>文件不存在!</font>"
exit
}
if($file['size']>$max_size){ //判断文件大小是否大于500000字节
echo "<font color='#FF0000'>上传文件太大!</font>"
exit
}
if(!in_array($file['type'],$arrType)){ //判断图片文件的格式
echo "<font color='#FF0000'>上传文件格式不对!</font>xxx:".$file['type']
exit
}
if(!file_exists($upfile)){ // 判断存放文件目录是否存在
mkdir($upfile,0777,true)
}
$imageSize=getimagesize($file['tmp_name'])
$img=$imageSize[0].'*'.$imageSize[1]
$fname=$file['name']
$ftype=explode('.',$fname)
$picName=$upfile."/cloudy".$fname
if(file_exists($picName)){
//echo "<font color='#FF0000'>同文件名已存在!</font>"
//exit
}
if(!move_uploaded_file($file['tmp_name'],$picName)){
echo "<font color='#FF0000'>移动文件出错!</font>"
exit
}
else{
/*
echo "<font color='#FF0000'>图片文件上传成功!</font><br/>"
echo "<font color='#0000FF'>图片大小:$img</font><br/>"
echo "图片预览:<br><div style='border:#F00 1px solid width:200pxheight:200px'>
<img src=\"".$picName."\" width=200px height=200px>".$fname."</div>"
*/
echo '{"imgurl":"http://localhost/uploads/cloudy'.$fname.'"}'
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)