`
xiyuliuguang
  • 浏览: 31297 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

Uploadify 上传文件

阅读更多
JSP代码
$(document).ready(function() {
[/align][align=left]
$.excelUploadify("#upload", "information", "上传文件");
});

$.extend({
excelUploadify : function (obj, importType, buttonText) {
$(obj).uploadify({
'uploader' : "js/uploadify/uploadify.swf",
'script' : "<%=basePath%>/InformationUpload.do",
'cancelImg' : "js/uploadify/cancel.png",
'auto' : true,
'multi' : false,
'queueID' : "fileQueue",
'fileDataName' : "upload",
'fileExt' :  "*.xls; *.doc; *.pdf; *.ppt; *.docx; *.xlsx; *.pptx; *.txt; *.jpg; *.png; *.gif; *.mts; *.mpg",
'fileDesc' : "支持文件; *.xls; *.doc; *.pdf; *.ppt; *.docx; *.xlsx; *.pptx; *.txt; *.jpg; *.png; *.gif; *.mts; *.mpg",
'sizeLimit' : '104857600',
'buttonText' : buttonText,
'scriptData' : {'importType' : importType},
'onSelect' :  function(event,ID,fileObj) {
//解决中文问题
$('#upload').uploadifySettings('scriptData',{'filename': encodeURI(encodeURI(fileObj.name)),'type' : 'upload'});
}, 
'onComplete' : function(event, queueID, fileObj, response, data) {

}
});
}
});

<!-- 上传 -->
                    <div  style="float:right;margin-right:10px;background-image:none; background-color:none;">
<table width="20" border="0" align="right">
  <tr>
    <td>
<div align="right" >
    <input id="upload" name="upload" type="file" style="background-image:none; background-color:none;" />
    </div>
    <div id="fileQueue" align="left"></div>
    </td>
  </tr>
</table>
  </div>


后台:

package cn.com.sundy.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.com.sundy.manager.ConverterService;
import cn.com.sundy.util.ImageThumb;
import cn.com.sundy.util.TimeSource;

import com.opensymphony.xwork2.ActionSupport;

/**
*
* @author WangMeng
*/
@Scope("prototype")
@Controller("informationUploadAction")
public class InformationUploadAction extends ActionSupport implements ServletContextAware,RequestAware,SessionAware,ServletResponseAware{


private static Logger log = Logger.getLogger(InformationUploadAction.class);
private Map<String,Object> request;
private Map<String,Object> session;
private HttpServletResponse response;
private ServletContext servletContext;

private String[] upload;

private String uploadContentType;

private String uploadFileName;

private String allowTypes;

private String savePath;

private String serverSavedName;

private String importType;

private String saveDir = "file\\temp\\upload\\data";

//文件分割符
private String seprater="\\";

@Autowired
ConverterService converterService;

public Map<String, Object> getRequest() {
return request;
}
public void setRequest(Map<String, Object> request) {
this.request = request;
}
public Map<String, Object> getSession() {
return session;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}

/**
* 上传
*
* @return
* @throws Exception
*/
public String upload() throws Exception {

//设置回写部分
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// 判断是否允许上传
String[] allowedTypes = getAllowTypes().split(",");
String filterResult = filterType(allowedTypes);

if (filterResult != null) {
return filterResult;
}
String randomTimeMillis = TimeSource.getNowTime14() + String.valueOf(System.currentTimeMillis());
String name1 = java.net.URLDecoder.decode(ServletActionContext.getRequest().getParameter("filename"), "utf-8").toLowerCase();
this.setUploadFileName(this.generatFileName(name1, randomTimeMillis));
// 以服务器的文件保存地址和原文件名建立上传文件输出流
File source = new File(getUpload()[0]);
serverSavedName = getSavePath() + "\\" + getUploadFileName();
String pdfName = serverSavedName.substring(0, serverSavedName.lastIndexOf(".")) + ".pdf";
//随机生成存到数据库中
String swfName = randomTimeMillis + ".swf";


PrintWriter out = response.getWriter();
try{
File serverSavedFile = new File(serverSavedName);
if (!serverSavedFile.exists() || !serverSavedFile.isFile()) {
File parent = serverSavedFile.getParentFile();
if (!parent.exists() || !parent.isDirectory()) {
parent.mkdirs();
}
serverSavedFile.createNewFile();
}

FileOutputStream fileOutputStream = new FileOutputStream(serverSavedFile);
FileInputStream fileInputStream = new FileInputStream(source);

byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}

fileInputStream.close();
fileOutputStream.close();

}

}catch(IOException e){
out.println("<script>alert('上传失败')</script>");
out.flush();
out.close();
return null;
}


String user = (String) session.get("username");
//上传人,上传时间,文件路径
out.print(user  + "," + TimeSource.getNowTime19() + "," + this.saveDir + this.seprater + name1 + ","  + this.saveDir + this.seprater + swfName + "," + this.saveDir + this.seprater + this.getUploadFileName() + "," + this.saveDir + this.seprater + SaveImageThumbName + "," + this.saveDir + this.seprater + SaveImageIndexName);
out.flush();
out.close();
return null;
}




/**
* 生成新文件名
* @param fileName
* @param randomTimeMillis
* @return
*/
public String generatFileName(String fileName, String randomTimeMillis){

String randomFileName = fileName.substring(0, fileName.trim().lastIndexOf(".")) + randomTimeMillis + fileName.substring(fileName.lastIndexOf("."));
return randomFileName;
}



/************************ Assistant ***********************/

/**
* 过滤上传类型
*
* @param types
* @return
*/
public String filterType(String[] types) {
String fileType = this.getUploadContentType();
System.out.println("fileType:" + fileType);
for (String type : types) {
if (type.equals(fileType)) {
return null;
}
}
return INPUT;
}

/************************ Getter & Setter ***********************/

public String[] getUpload() {
return upload;
}

public void setUpload(String[] upload) {
this.upload = upload;
}

public String getUploadContentType() {
return uploadContentType;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public String getUploadFileName() {
return uploadFileName;
}

public void setUploadFileName(String uploadFileName) throws UnsupportedEncodingException {
this.uploadFileName = uploadFileName;
}

public String getAllowTypes() {
return allowTypes;
}

public void setAllowTypes(String allowTypes) {
this.allowTypes = allowTypes;
}

public String getSavePath() {
return servletContext.getRealPath(savePath);
}

public void setSavePath(String savePath) {
this.savePath = savePath;
}

public String getServerSavedName() {
return serverSavedName;
}

public void setServerSavedName(String serverSavedName) {
this.serverSavedName = serverSavedName;
}

@Override
public void setServletContext(ServletContext arg0) {
this.servletContext = arg0;
}

public String getImportType() {
return importType;
}

public void setImportType(String importType) {
this.importType = importType;
}

public ServletContext getServletContext() {
return servletContext;
}
@Override
public void setServletResponse(HttpServletResponse arg0) {
this.response=arg0;

}
public String getSaveDir() {
return saveDir;
}
public void setSaveDir(String saveDir) {
this.saveDir = saveDir;
}
public String getSeprater() {
return seprater;
}
public void setSeprater(String seprater) {
this.seprater = seprater;
}


}
//struts
<action name="InformationUpload" class="informationUploadAction" method="upload" >
<param name="allowTypes">
application/msexcel,application/vnd.ms-excel,application/octet-stream <!-- Separated by ',' -->
</param>
</action>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics