import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import javax.mail.internet.MimeUtility;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; @Controller
@RequestMapping("/commonUpload")
public class CommonUploadContorller{ @Autowired
private CommonService centerCommonService; /**
* 添加资料页
*
* @return
* @author guogf
*/
@RequestMapping("/toUploadAttachment")
public String toUploadAttachment(String blongId,String fileSource,Model model) {
Map<String, Object> objMap = new HashMap<String, Object>();
objMap.put("belongId", blongId);
objMap.put("fileSource", fileSource);
model.addAttribute("objMap", objMap);
return "commonUpload/uploadAttachment";
} @RequestMapping("/fileUpLoad")
public String fileUpLoad(HttpServletRequest request,HttpServletResponse response,long belongId
,@RequestParam(defaultValue = "100") String fileSource, @RequestParam(value="file",required=false)MultipartFile file) {
User currentUser = UserUtils.getUser();
String attachmentId = centerCommonService.uploadAttachment(belongId,fileSource, file, currentUser);
if(!"uploadError".equals(attachmentId)){
try {
response.reset();
PrintWriter out = response.getWriter();
out.print("{\"attachmentId\" :"+ attachmentId+"}");
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}else{
return null;
}
} /**
* 资料附件下载
* @param files
* @return
* @author guogf
*/
@RequestMapping("/downLoadAttachment")
@ResponseBody
public void downLoadAttachment(HttpServletRequest request,String attachId,HttpServletResponse response){
FTPUtils ftpUtils = FTPUtils.getInstance();
InputStream is = null;
ServletOutputStream out;
byte[] content = new byte[1024];
String fileName = "";
List<Attachment> attachList = centerCommonService.findAttList(attachId.split(","));
if(attachList!=null && attachList.size()>1){//批量下载多个文件,先压缩,再下载
try {
response.addHeader("Content-Disposition", "attachment; filename="+IdGen.getRandomName(6)+DateUtils.getNumberDateTime()+".zip");
ServletOutputStream sos=response.getOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(sos));
int readLen = -1;
for(Attachment att : attachList){
ZipEntry entry = new ZipEntry(att.getFilePath());
zipOut.putNextEntry(entry);
is = ftpUtils.retrieveFile(att.getFilePath().substring(0, att.getFilePath().lastIndexOf("/"))
,att.getFilePath().split("/")[att.getFilePath().split("/").length-1]);
if(is!=null){
while ((readLen = is.read(content, 0, 1024)) != -1) {
zipOut.write(content, 0, readLen);
}
is.close();
}
}
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}else if(attachList!=null && attachList.size()==1){//下载单个文件,直接下载
Attachment att = attachList.get(0);
fileName = att.getFileName();
try {
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("X-Accel-Charset", "UTF-8");
response.setHeader("Content-Disposition", "attachment;" + encode(request, fileName));
is = ftpUtils.retrieveFile(att.getFilePath().substring(0, att.getFilePath().lastIndexOf("/"))
,att.getFilePath().split("/")[att.getFilePath().split("/").length-1]);
out = response.getOutputStream();
int length = 0;
while ((length = is.read(content)) != -1) {
out.write(content, 0, length);
}
out.write(content);
out.flush();
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // IE与firefox下载区分
private String encode(HttpServletRequest request, String realfileName) {
String agent = request.getHeader("USER-AGENT").toLowerCase();
try {
String new_filename = URLEncoder.encode(realfileName, "UTF8");
// IE
if (null != agent && -1 != agent.indexOf("msie")) {
realfileName = URLEncoder.encode(realfileName, "UTF8")
.replaceAll("\\+", "%20");
realfileName ="filename="+ new String(realfileName.getBytes("GBK"),
"iso-8859-1");
// Firefox
}
// Opera浏览器只能采用filename*
else if (null != agent && agent.indexOf("opera") != -1)
{
realfileName = "filename*=UTF-8''" + new_filename;
}
// Safari浏览器,只能采用ISO编码的中文输出
else if (null != agent && agent.indexOf("safari") != -1 )
{
realfileName = "filename=\"" + new String(realfileName.getBytes("UTF-8"),"ISO8859-1") + "\"";
}
// Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出
else if (null != agent && agent.indexOf("applewebkit") != -1 )
{
new_filename = MimeUtility.encodeText(realfileName, "UTF8", "B");
realfileName = "filename=\"" + new_filename + "\"";
}
// FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出
else if (null != agent && -1 != agent.indexOf("mozilla")) {
// realfileName = MimeUtility
// .encodeText(realfileName, "UTF8", "B");
// realfileName = "filename=?UTF-8?B?" + (new String(Encodes.encodeBase64(realfileName.getBytes("UTF-8")))) + "?=";
realfileName = "filename*=UTF-8''" + new_filename;
}
} catch (UnsupportedEncodingException e) {
try {
realfileName = new String(realfileName.getBytes("UTF-8"),
"iso-8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return realfileName;
}
}
 var uploader;
$(function(){
//下面是文件上传的js操作
var $ = jQuery,
$list = $('#thelist'),
$btn = $('#ctlBtn'),
state = 'pending', uploader = WebUploader.create({
// 不压缩image
resize: false,
// swf文件路径
swf: ctxStatic+'/WebUploader/Uploader.swf',
// 文件接收服务端。
server: ctx+'/commonUpload/fileUpLoad',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick:{
id:'#picker',
multiple :true
},
formData: {
belongId:$('#belongId').val(),
fileSource:$('#fileSource').val()
}
});
// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
$list.append( '<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name +
'<a id="delete_' + file.id + '" class="file_close" title="删除" href="javascript:void(0);" fileId="" />'+'</h4>' +
'<p class="state">等待上传...</p>' +
'</div>' );
$('#delete_'+ file.id).on('click', function() {
if($(this).attr("fileId")!=''){
var attachmentIds = $("#attachmentIds").val();
var arrList = attachmentIds.split(',');
arrList.splice($.inArray($(this).attr("fileId"),arrList),1);
$("#attachmentIds").val(arrList.join(','));
}
$('#'+file.id).remove();
uploader.removeFile( file );
});
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress .progress-bar');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('<div class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" style="width: 0%">' +
'</div>' +
'</div>').appendTo( $li ).find('.progress-bar');
} $li.find('p.state').text('上传中'); $percent.css( 'width', percentage * 100 + '%' );
});
uploader.on( 'uploadSuccess', function( file,response ) {
var num = $('#attachmentIds').val();
$('#attachmentIds').val(num+","+response.attachmentId);
$( '#'+file.id ).find('p.state').text('已上传');
$('#delete_'+ file.id).attr("fileId",response.attachmentId);
});
uploader.on( 'uploadError', function( file,reason ) {
$( '#'+file.id ).find('p.state').text('上传出错');
});
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').fadeOut();
});
$btn.on( 'click', function() {
if ( state === 'uploading' ) {
uploader.stop();
} else {
uploader.upload();
}
});
uploader.on( 'all', function( type ) {
if ( type === 'startUpload' ) {
state = 'uploading';
} else if ( type === 'stopUpload' ) {
state = 'paused';
} else if ( type === 'uploadFinished' ) {
state = 'done';
} if ( state === 'uploading' ) {
$btn.text('暂停上传');
} else {
$btn.text('开始上传');
}
});
});
var deleteFile = function(id){
var attachmentIds = $("#attachmentIds").val();
var arrList = attachmentIds.split(',');
arrList.splice($.inArray(id,arrList),1);
$("#attachmentIds").val(arrList.join(','));
$('#file_lable_'+id).remove();
};
05-11 17:35