js
$(document).ready(function() {
$("#apkIcon").uploadify({
'swf' : 'js/upload/uploadify.swf',
'uploader' : 'action_upload.action',
'cancel' : 'js/upload/uploadify-cancel.png',
'buttonClass' : 'uploadify-button',
'fromData' : '{'id':'${"#apkIcon"}.val()'}',
'fileObjName' : 'apkIcon',
'buttonImage' : 'js/upload/apk_ctw.gif',
'progressData' : 'percentage',
'removeCompleted': false,
'method' : 'post',
'fileTypeExts' : '*.png;*.gif;',
'width' : '65',
'height' : '30',
'fileSizeLimit' : '256KB',
'auto' : true,
'multi' : true,
'onUploadStart' : function(file) {
alert(file.name);
$("#icon").attr("value",file.name);
alert($("#icon").val()); },
onUploadSuccess:function(file,data,response){
if(response){
$("#icondiv").html("<img src='"+data+"'>");
}else{
alert('上传发生错误');
}
},
'onUploadError':function(file,errorCode,errorMsg,errorString){
alert('只能上传不大于256KB的图片文件');
},
'onQueueComplete': function (event, data) {
// if(data.filesUploaded>=1){
// alert('上传成功');
// }
}
}); });
jsp:
<input type="file" id="apkIcon" name="apkIcon" >
action
public void upload(){
//File imageFile=new File(ServletActionContext.getServletContext().getRealPath("/uploads")+"/"+param);
//upload(up, imageFile);
try {
// 用于设定诸如缓存之类的参数,和性能相关
// 此处用默认设定
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 解析表单中的数据
ServletFileUpload upload = new ServletFileUpload(dfif);
//upload.setSizeMax(10 * 1024 * 1024); // 允许上传的最大值 List list =upload.parseRequest(ServletActionContext.getRequest()); // 开始解析request对象中的表单数据
String id=ServletActionContext.getRequest().getParameter("id");
// list中是FileItem对象
// 一个FileItem用于封装一个上传的文件数据
if (list.size() >= 1) {
FileItem item = (FileItem) list.get(0);
// 获得上文件的路径名
String name = item.getName();
name = name.substring(name.lastIndexOf("\\") + 1); // 把上传的文件数据写入本地文(服务器端)件文件夹的名字为upload
String path = "uploads"; // Sun的标准,服务器实现的API
ServletContext ctx = ServletActionContext.getServletContext(); path = ctx.getRealPath(path);
File file = new File(path);
if(!file.exists()){
System.out.println("创建文件夹");
file.mkdir();
} System.out.println(path);
System.out.println(name);
//将文件放到指定的地方
item.write(new File(path, name));
}
} catch (Exception e) {
System.out.print("文件上传失败");
}
String savePath=ServletActionContext.getServletContext().getRealPath("")+"/uploads/";
try{
File folder=new File(savePath);
String filePath="C:\\Documents and Settings\\Administrator\\桌面\\R7TU[}VOOFGQQ~0)MY3IQJI.gif";//ServletActionContext.getRequest().getParameter("apkVO.apk.apkIcon");
if(!folder.exists()){
folder.mkdirs();
}
// File outFile=new File(savePath));
FileOutputStream outStream = new FileOutputStream(folder);
FileInputStream inStream = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int l = 0;
while ((l = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, l);
}
inStream.close();
outStream.close();
}catch (Exception e) {
}
}
action中方法是从网上找的,是两种方式取值,但是都取不到,我要把上传的图片或者文件写入服务器uploads文件夹下,在action中我不知道怎么取值和操作,弄了好久了,知道的大侠指点下,有具体的例子就更好,跪求啊。
$(document).ready(function() {
$("#apkIcon").uploadify({
'swf' : 'js/upload/uploadify.swf',
'uploader' : 'action_upload.action',
'cancel' : 'js/upload/uploadify-cancel.png',
'buttonClass' : 'uploadify-button',
'fromData' : '{'id':'${"#apkIcon"}.val()'}',
'fileObjName' : 'apkIcon',
'buttonImage' : 'js/upload/apk_ctw.gif',
'progressData' : 'percentage',
'removeCompleted': false,
'method' : 'post',
'fileTypeExts' : '*.png;*.gif;',
'width' : '65',
'height' : '30',
'fileSizeLimit' : '256KB',
'auto' : true,
'multi' : true,
'onUploadStart' : function(file) {
alert(file.name);
$("#icon").attr("value",file.name);
alert($("#icon").val()); },
onUploadSuccess:function(file,data,response){
if(response){
$("#icondiv").html("<img src='"+data+"'>");
}else{
alert('上传发生错误');
}
},
'onUploadError':function(file,errorCode,errorMsg,errorString){
alert('只能上传不大于256KB的图片文件');
},
'onQueueComplete': function (event, data) {
// if(data.filesUploaded>=1){
// alert('上传成功');
// }
}
}); });
jsp:
<input type="file" id="apkIcon" name="apkIcon" >
action
public void upload(){
//File imageFile=new File(ServletActionContext.getServletContext().getRealPath("/uploads")+"/"+param);
//upload(up, imageFile);
try {
// 用于设定诸如缓存之类的参数,和性能相关
// 此处用默认设定
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 解析表单中的数据
ServletFileUpload upload = new ServletFileUpload(dfif);
//upload.setSizeMax(10 * 1024 * 1024); // 允许上传的最大值 List list =upload.parseRequest(ServletActionContext.getRequest()); // 开始解析request对象中的表单数据
String id=ServletActionContext.getRequest().getParameter("id");
// list中是FileItem对象
// 一个FileItem用于封装一个上传的文件数据
if (list.size() >= 1) {
FileItem item = (FileItem) list.get(0);
// 获得上文件的路径名
String name = item.getName();
name = name.substring(name.lastIndexOf("\\") + 1); // 把上传的文件数据写入本地文(服务器端)件文件夹的名字为upload
String path = "uploads"; // Sun的标准,服务器实现的API
ServletContext ctx = ServletActionContext.getServletContext(); path = ctx.getRealPath(path);
File file = new File(path);
if(!file.exists()){
System.out.println("创建文件夹");
file.mkdir();
} System.out.println(path);
System.out.println(name);
//将文件放到指定的地方
item.write(new File(path, name));
}
} catch (Exception e) {
System.out.print("文件上传失败");
}
String savePath=ServletActionContext.getServletContext().getRealPath("")+"/uploads/";
try{
File folder=new File(savePath);
String filePath="C:\\Documents and Settings\\Administrator\\桌面\\R7TU[}VOOFGQQ~0)MY3IQJI.gif";//ServletActionContext.getRequest().getParameter("apkVO.apk.apkIcon");
if(!folder.exists()){
folder.mkdirs();
}
// File outFile=new File(savePath));
FileOutputStream outStream = new FileOutputStream(folder);
FileInputStream inStream = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int l = 0;
while ((l = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, l);
}
inStream.close();
outStream.close();
}catch (Exception e) {
}
}
action中方法是从网上找的,是两种方式取值,但是都取不到,我要把上传的图片或者文件写入服务器uploads文件夹下,在action中我不知道怎么取值和操作,弄了好久了,知道的大侠指点下,有具体的例子就更好,跪求啊。
private String apkIconName;加上get set 方法 用apkIcon就是你想要得到的数据
页面jshtml:
<input type="file" style="width:403px; height:19px; line-height:19px; border:1px solid #c9caca;" name="uploadify" id="uploadify" />
<div id="fileQueue"></div>
<div id="resData" ></div>
js:
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
'uploader' : '/js/uploadify/uploadify.swf',
'script' : '/upload.jsp',//action的路径
'method' : 'GET', //如果要传参数,就必须改为GET
'cancelImg' : '/js/uploadify/cancel.png',
'fileDataName' : 'uploadify',//和input的name属性值保持一致就好
'queueID' : 'fileQueue',
'folder' : 'uploadfiles',
'auto' : false, //选定文件后是否自动上传,默认false
'simUploadLimit' : 1, //一次同步上传的文件数目
'sizeLimit' : 1024*1024, //设置单个文件大小限制,单位为byte
'buttonImg' : '/js/uploadify/select.jpg',
'height' : '21',
'width' : '90',
'queueSizeLimit' : 1, //限制在一次队列中的次数(可选定几个文件)。默认值= 999,而一次可传几个文件有 simUploadLimit属性决定。
'fileDesc' : '支持格式:jpg', //如果配置了以下的'fileExt'属性,那么这个属性是必须的
'fileExt' : '*.jpg',//允许的格式
'onComplete' : function(event, ID, fileObj, response, data) {
var file = document.getElementById('filename').value;
document.getElementById('filename').value=file+","+response;
},
'onAllComplete' : function(event,data) {
document.caseForm.submit();
}
});
});
</script>upload.jsp<%@ page contentType="text/html; charset=utf-8" language="java" errorPage="" %>
<%@ page language="java" import="java.io.PrintWriter"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.util.UUID"%>
<%@ page language="java" import="java.util.Enumeration"%>
<%@ page language="java" import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.FileRenamePolicy"%><%
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("utf-8");
PrintWriter xmlout = response.getWriter();
String uuid = UUID.randomUUID().toString();
//文件的fileURL
String fileURL = "";
// 上传文件名
String fileName = null;
StringBuffer sb = new StringBuffer();
String result = ""; try
{
//得到此源文件的目录
String realPath = getServletContext().getRealPath("");
String contentPath = request.getContextPath();
String requestURL = request.getRequestURL().toString();
String realURL = requestURL.split(contentPath)[0] + contentPath;
//上传文件存放的文件夹名称,一律放在根目录下的文件夹里面即folderName/
String type = request.getParameter("type");
String folderName = "/uploadfiles";
// 将上传文件存放在saveDirectory
String saveDirectory = realPath + folderName;
System.out.println("saveDirectory= " + saveDirectory);
File uploadPath = new File(saveDirectory);
if (!uploadPath.exists())
{
uploadPath.mkdir();
}
// 上传文件的大小限制在20 MB
int maxPostSize = 25 * 1024 * 1024;
//实现将上传文件更名,以防同名覆盖和同时上传两个文件名相同的文件,自动在文件名后面加1(在1~9999范围内)
FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();
// 上传文件
MultipartRequest multi = new MultipartRequest(request,saveDirectory, maxPostSize, "UTF-8",policy); // 取得所有上传文件名称
Enumeration filesname = multi.getFileNames();
while (filesname.hasMoreElements())
{
String name = (String) filesname.nextElement();
//文件上传的完整路径
File f = multi.getFile(name);
//文件名称
fileName = multi.getFilesystemName(name);
System.out.println("name=="+name);
if (fileName != null)
{
String oldFilename=fileName;
int idx=oldFilename.lastIndexOf(".");
String extention=oldFilename.substring(idx);
//取文件名
//得到不重复的文件名,用uuid加文件名
String sServerFileName = uuid+extention;
File sServerFile= new File(saveDirectory+"\\" + sServerFileName);
f.renameTo(sServerFile);
String FileName = sServerFile.getName();
fileURL = folderName + "/" + FileName;
System.out.println("fileURL123=="+fileURL);
}
}
result = fileURL;
System.out.println(result);
}
catch(Exception e)
{
System.out.println("message=" + e.getMessage());
//Posted content length of 42654262 exceeds limit of 10485760
String message = e.getMessage();
if(message.indexOf("Posted content length of") !=-1)
{
String content = message.split("length of ")[1].split(" exceeds")[0];
int ct = Integer.parseInt(content);
String limit = message.split("limit of ")[1];
int lt = Integer.parseInt(limit);
result = "对不起,你上传的文件大小为" + ct/(1024*1024) + "MB,超过了最大限制" + lt/(1024*1024) + "MB" ;
}
else
{
result = "上传失败";
}
e.printStackTrace();
}
try
{
xmlout.write(result);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
xmlout.flush();
xmlout.close();
}
%>