springmvc +uploadify 3.2.1 上傳檔案
<%@page import="com.ist.pojo.User"%>
<%@page import="com.ist.constant.ConstantField"%>
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Upload</title>
<!--裝載檔案-->
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.uploadify.js" type="text/javascript"></script>
<script src="js/jquery.uploadify.min.js" type="text/javascript"></script>
<link href="uploadify.css" rel="stylesheet" type="text/css" />
<%User user = (User)request.getSession().getAttribute(ConstantField.LOGIN_USER); %>
<!--ready事件-->
<script type="text/javascript">
$(document).ready(function () {
var fileType ="${param.fileType}";
var userName = "<%=user.getUsName() %>";
$("#uploadify").uploadify({
'cancelImage': 'cancel.png',
'auto': false,
'successTimeout': 99999,
'swf': 'uploadify.swf',
'queueID': 'fileQueue',
'uploader': '../uploadDFS/upload.do?fileType='+fileType+'&userName='+userName,
'fileSizeLimit': '0',
'fileTypeExts': '*.gif; *.jpeg; *.jpg; *.png',
'multi': true,
'method':'post',
'queueSizeLimit': 10,
'buttonText':'選擇檔案',
//'formData': { 'fileType':1,'userName':'admin' },//這裡只能傳靜態引數
onSelectError: function (file, errorCode, errorMsg) {
switch (errorCode) {
case -100:
alert("上傳的檔案數量已經超出系統限制的" + $('#uploadify').uploadify('settings', 'queueSizeLimit') + "個檔案!");
break;
case -110:
alert("檔案 [" + file.name + "] 大小超出系統限制的" + $('#uploadify').uploadify('settings', 'fileSizeLimit') + "大小!");
break;
case -120:
alert("檔案 [" + file.name + "] 大小異常!");
break;
case -130:
alert("檔案 [" + file.name + "] 型別不正確!");
break;
}
},
'onUploadStart': function (file) {
var param = {};
param.fileType = fileType;
param.userName = userName;
$("#uploadify").uploadify("settings","formData",param);
//在onUploadStart事件中,也就是上傳之前,把引數寫好傳遞到後臺。
},'onUploadSuccess':function(file, data, response){
alert("檔案:" + file.name + "上傳成功");
},'onUploadError' : function(file, errorCode, errorMsg, errorString) {
alert("檔案:" + file.name + "上傳失敗");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div id="fileQueue">
</div>
<div>
<p>
<input type="file" name="uploadify" id="uploadify"/>
<input id="Button1" type="button" value="上傳" onclick="javascript: $('#uploadify').uploadify('upload','*')" />
<input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadify('cancel','*')" />
</p>
</div>
</form>
</body>
</html>
action類
@RequestMapping("/upload.do")
@ResponseBody
public String upload (HttpServletRequest request){
//request.getParameter()只能獲取url ?後面的引數
int fileType = Integer.parseInt(request.getParameter("fileType"));
String userName = request.getParameter("userName");
User user = new User();
user.setUsName(userName);
String path="";
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024) ;
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");//關鍵
upload.setSizeMax(200000000);
try {
//可以上傳多個檔案
List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
//獲取formdata引數
Map<String,Object> formData = getItemFiled(list);
for(int i=0;i<list.size();i++){
FileItem item = list.get(i);
if(!item.isFormField()){
String name = item.getName() ;
String fileExtName = name.substring(name.lastIndexOf(".")+1,name.length());
String oldName = name.replaceAll("." + fileExtName,"");
InputStream in = item.getInputStream();
byte[] content = getInputStreamToByte(in);
DFSFile dfsfile = new DFSFile(oldName, content,fileExtName,fileType);
dfsfile.setFileLength(item.getSize());
NameValuePair[] metaList = new NameValuePair[3];
metaList[0] = new NameValuePair("fileName", name);
metaList[1] = new NameValuePair("fileExtName", fileExtName);
metaList[2] = new NameValuePair("fileLength", String.valueOf(item.getSize()));
path = fastService.upload(dfsfile ,metaList,user);
break;
}
}
}catch (Exception e) {
System.out.println("出錯了:" + e.getMessage());
}
return "1";
}
/**
* 獲取uploadify的formdata Map集合
* @param list
* @return
*/
public Map<String,Object> getItemFiled(List<FileItem> list){
Map<String,Object> results = new HashMap<String,Object>();
for(int i=0;i<list.size();i++){
FileItem item = list.get(i);
if(item.isFormField()){
String key = item.getFieldName();
String value = item.getString();
results.put(key, value);
}
}
return results;
}
/**
* 把inputStream流轉換成位元組陣列
* @param in
* @return
*/
public byte[] getInputStreamToByte(InputStream in){
byte[] file_buff = null;
try{
if (in != null) {
int len = in.available();
file_buff = new byte[len];
in.read(file_buff);
}
}catch(Exception e){
System.out.println("出錯了:" + e.getMessage());
}
return file_buff;
}
service類
/**
* 檔案上傳
* @param file
* @return
*/
public String upload(DFSFile file,NameValuePair[] metaList,User user) {
log.info("File Name: " + file.getName() + " File Length: " + file.getContent().length);
//NameValuePair[] meta_list = new NameValuePair[3];
//meta_list[0] = new NameValuePair("width", "120");
//meta_list[1] = new NameValuePair("heigth", "120");
//meta_list[2] = new NameValuePair("author", "admin");
long startTime = System.currentTimeMillis();
String[] uploadResults = null;
try {
uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), metaList);
} catch (IOException e) {
log.error("io異常:上傳檔案 " + file.getName(), e);
} catch (Exception e) {
log.error("非io異常:上傳檔案 " + file.getName(), e);
}
log.info("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms");
if (uploadResults == null) {
log.error("上傳檔案失敗, 錯誤碼: " + storageClient.getErrorCode());
}
String groupName = uploadResults[0];
String remoteFileName = uploadResults[1];
//儲存Marterial素材物件和FileType檔案物件
saveMarterialAndFileType(user, file, remoteFileName);
String fileAbsolutePath = ConstantField.PROTOCOL + trackerServer.getInetSocketAddress().getHostName() + ConstantField.SEPARATOR
+ ConstantField.TRACKER_NGNIX_PORT + ConstantField.SEPARATOR + groupName + ConstantField.SEPARATOR + remoteFileName;
log.info("上傳檔案成功! " + "組名: " + groupName + ", 檔名:" + " "
+ remoteFileName);
return fileAbsolutePath;
}
dfsfile類
public class DFSFile {
//原檔名稱,不含結尾字串
private String name;
//檔案內容 位元組型別
private byte[] content;
//檔案結尾
private String ext;
private String height;
private String width;
private String author;
private Long fileLength;
private int fileType;
public DFSFile(String name, byte[] content, String ext, String height,
String width, String author,int fileType) {
super();
this.name = name;
this.content = content;
this.ext = ext;
this.height = height;
this.width = width;
this.author = author;
this.fileType = fileType;
}
public DFSFile(String name, byte[] content, String ext,int fileType) {
super();
this.name = name;
this.content = content;
this.ext = ext;
this.fileType = fileType;
}
public DFSFile(String ext,Long fileLength,int fileType) {
this.ext = ext;
this.fileLength = fileLength;
this.fileType = fileType;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getFileLength() {
return fileLength;
}
public void setFileLength(Long fileLength) {
this.fileLength = fileLength;
}
public int getFileType() {
return fileType;
}
public void setFileType(int fileType) {
this.fileType = fileType;
}
}