文件上传和文件压缩下载


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;



@Controller
@RequestMapping("/file")
public class FileController extends BaseAction {


private final static Logger log = LoggerFactory.getLogger(FileController.class);


private static long MAXSIZE = 500000;

private static int CACHE_BYTE_LENGTH=1024;
private static String COMMA=",";


private static String allowFileExt = ".png,.jpg,.jpeg,.xls,.pdf,.doc,.rar,.zip,.txt,.mp3,.mp4,.avi";

private static String savedFileExt = ".png";


private static String imgFileExt = ".png,.jpg,.jpeg";

private static String picStorepath = null;
    @Autowired
    private IExtConfigparamService extConfigparamService;
@PostConstruct
public void init() {
if (ResourceUtil.getAllowFileext() != null) {
allowFileExt = ResourceUtil.getAllowFileext();
}
picStorepath=extConfigparamService.fetchValue(Constant.PIC_STOREPATH);

if(StringUtils.isNotEmpty(picStorepath)){
picStorepath=picStorepath+"/";
}
}

public static void deleteZip(String realPath){
        // 根据路径获取文件对象
        File file = new File(realPath);
        // 判断文件是否存在
        if (file.exists()) {
            // 文件删除
            file.delete();
            System.out.println("删除成功"+realPath);
        }
}

public static void deleteFile(File f){
    for(File fi:f.listFiles()){
        if(fi.isDirectory()){
        deleteFile(fi);
        }
        else{
            fi.delete();
        }
    }
    f.delete();
}


@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) {
try {
System.out.println("lai");
String cusId = request.getParameter("cus_id");
String applyId = request.getParameter("apply_id");
//文件夹路径
        String src= getPath("/WEB-INF/upload/PLS/"+cusId+"/"+applyId);
        //拷贝将要压缩文件路径
        String path = getPath("/WEB-INF/upload/PLS/"+cusId+"/"+applyId)+"1";
        //复制一份 修改名字 压缩下载
        CopyDirectory.copy(src, path);
        File file= new File(path);
        UpdateFileName.renameFile(file);
        new CompactAlgorithm(new File(path+"/../",applyId+".zip")).zipFiles(file);  
       
        String filename = applyId+".zip";
        //压缩文件全
        String realPath = path+"/../" +applyId+".zip";
            InputStream fis = new BufferedInputStream(new FileInputStream(realPath));
            response.setHeader("Content-Disposition","attachment;filename="+filename);
            byte [] bts = new byte [CACHE_BYTE_LENGTH];
    int len = 0;
    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
    while((len=fis.read(bts, 0, CACHE_BYTE_LENGTH))!=-1){
    outputStream.write(bts, 0, len);
    }
    outputStream.flush();
    fis.close();
    outputStream.close();
    deleteFile(file);
    deleteZip(realPath);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
      
    }


@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(@RequestParam(value = "file") MultipartFile file,
@RequestParam(value = "files") MultipartFile[] files, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
// 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解
// 并且上传多个文件时,前台表单中的所有<input
// type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
// enctype = "multipart/form-data"
Map<String, Object> context = new HashMap<>(5);
List<String> fileNames = new ArrayList<>();

for (int i=0;i<files.length;i++) {
fileNames.add(uploadFile(i,files[i], request, response));
}


fileNames.add(uploadFile(0,file, request, response));
context.put(SUCCESS, true);
context.put("data", fileNames);
context.put("statusCode", "200");
context.put("filename", fileNames);


HtmlUtil.writerJson(response, context);
}


/**
* 获取文件路径
* 注:优先从配置文件中获取
*/
private String getPath(String path) {

String filePath = ResourceUtil.getFilePath();
if (StringUtils.isNotEmpty(filePath)) {
return ResourceUtil.getFilePath() + path;
}


WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
if (webApplicationContext != null) {
ServletContext servletContext = webApplicationContext.getServletContext();
return servletContext.getRealPath(path);
}

return path;
}

@RequestMapping(value = "/imageUrl", method = RequestMethod.GET)
public void imageUrl(HttpServletRequest request, HttpServletResponse response) throws IOException{
String path = request.getParameter("path");
String supportall = request.getParameter("supportall");
String directopen = request.getParameter("directopen");
String template = request.getParameter("template");
String loadpath=null;
if(template==null){
loadpath="/WEB-INF/upload/"+picStorepath;
}else{
loadpath="/WEB-INF/filetemplate/";
}
imageUrl(path,supportall,directopen,loadpath,response);
}

@RequestMapping(value = "/imageTemplateUrl", method = RequestMethod.GET)
public void imageTemplateUrl(HttpServletRequest request, HttpServletResponse response) throws IOException{
String path = request.getParameter("path");
String supportall = request.getParameter("supportall");
String directopen = request.getParameter("directopen");
imageUrl(path,supportall,directopen,"/WEB-INF/filetemplate/",response);
}

private void imageUrl(String path,String supportall,String directopen,String filePath,HttpServletResponse response) throws IOException{
boolean isimage=false;
String suffix=savedFileExt;
String realPath = getPath(filePath);
log.debug("realPath-----------------:"+realPath);

String filename=null;
String filepath=null;
int separatorIndex=path.lastIndexOf("/");
if(separatorIndex!=-1){
filename=path.substring(separatorIndex+1);
filepath=path.substring(0, separatorIndex);
}else{
filename=path;
}

if(!path.endsWith(suffix)){

String filePackage=realPath;
if(filepath!=null){
filePackage=realPath+File.separator+filepath;
}

File[] fs = new File(filePackage).listFiles();

if(fs!=null){
long lastModified=0;
for(File f:fs){
if(f.getName().startsWith(filename)){
if(f.lastModified()==lastModified&&f.getName().endsWith(savedFileExt)){
suffix=savedFileExt;
}else if(f.lastModified()>lastModified){
lastModified=f.lastModified();
suffix=StringUtils.remove(f.getName(),filename);
}
}
}
path=path+suffix;
}
}

if(imgFileExt.indexOf(suffix)!=-1){
isimage=true;
}

String contenttype="image/png";
File picFile = new File(realPath+File.separator+path);
log.debug("picFile-----------------:"+picFile.getPath());
if (!picFile.exists()) {
path = StringUtils.remove(realPath,picStorepath.replace("/", "")) + "/error.jpg";
picFile = new File(path);
suffix=savedFileExt;
}else if(!isimage&&supportall==null){
//不是图片,且为缩图,则用虚拟缩图
path = StringUtils.remove(realPath,picStorepath.replace("/", "")) + "/notimg.jpg";
picFile = new File(path);
suffix=savedFileExt;
}else{
response.setHeader("Cache-Control", "no-cache");  
response.setHeader("Cache-Control", "no-store");  
response.setHeader("Pragma", "no-cache");  
response.setDateHeader("Expires", 0);

switch(suffix){
case ".png":
contenttype="image/png";
break;
case ".jpg":
contenttype="image/jpg";
break;
case ".jpeg":
contenttype="image/jpeg";
break;
case ".xls":
contenttype="application/x-xls";
break;
case ".pdf":
contenttype="application/pdf";
break;
case ".zip":
contenttype="application/zip";
break;
case ".rar":
contenttype="application/octet-stream";
break;
default:
contenttype="image/png";
break;
}
}

response.setContentType(contenttype+"; charset=GBK");
if(directopen==null){
//直接打开,则不需要加下面这句
response.setHeader("Content-Disposition", "attachment; filename="+new String((filename+suffix).getBytes("GBK"),"ISO8859_1"));
}
ServletOutputStream outputStream=null;
FileInputStream inputStream=null;
try {
outputStream = response.getOutputStream();
inputStream = new FileInputStream(picFile);
byte[] buffer = new byte[1024];
int i = -1;
while ((i = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(outputStream!=null){
outputStream.flush();
outputStream.close();
outputStream = null;
}
if(inputStream!=null){
inputStream.close();
}
}
}

private String uploadFile(int i,MultipartFile e, HttpServletRequest request, HttpServletResponse response)
throws Exception {
if (e.isEmpty()) {
log.debug("文件未上传");
} else {
log.debug("文件长度: " + e.getSize());
log.debug("文件类型: " + e.getContentType());
log.debug("文件名称: " + e.getName());
log.debug("文件原名: " + e.getOriginalFilename());


if (e.getSize() > MAXSIZE) {
sendFailureMessage(response, e.getName() + "上传文件超出限制大小!");
return null;
}


String fileExt = "."
+ e.getOriginalFilename().substring(e.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String>asList(allowFileExt.split(COMMA)).contains(fileExt)) {
sendFailureMessage(response, "上传文件扩展名是不允许的扩展名。\n只允许" + allowFileExt + "格式!");
return null;
}


String dir=request.getParameter("dir");
String picname=request.getParameter("picname");
if(i!=0){
picname=picname+i;
}
String realPath = getPath("/WEB-INF/upload/"+picStorepath+dir);
// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的

File fileDest = new File(realPath);


// 如果目标文件夹不存在
if (!fileDest.isDirectory() || !fileDest.exists()) {
if (!fileDest.mkdirs()) {
log.debug("目录文件夹不存,在创建目标文件夹时失败!");
return null;
}
}
// File srcFile = new File(realPath, picname+savedFileExt);//e.getOriginalFilename()  +fileExt
//e.getOriginalFilename()  +fileExt
File srcFile = new File(realPath, picname+fileExt);
System.out.println(srcFile.getAbsolutePath());
e.transferTo(srcFile);
return srcFile.getName();
}
return null;
}


}

猜你喜欢

转载自blog.csdn.net/weixin_39225655/article/details/78190778