文件的上传与下载

package com.chinacoal.asset.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
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;

import com.chinacoal.asset.model.Profile;
import com.chinacoal.asset.utils.FileUtil;
import com.chinacoal.asset.utils.RequestUtil;
import com.chinacoal.asset.utils.ResultCode;
import com.chinacoal.asset.utils.ValidationUtil;

@Controller
@RequestMapping("/common")
public class FileCommonController {
	Logger log=Logger.getLogger(FileCommonController.class);

	/**
	 * 以字符串格式存取数据
	 * @param image
	 * @param dir
	 * @param width
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/web-upload-base64")
	@ResponseBody
	public ResultCode<String> webUploadFileBase64(@RequestParam(value = "image", required = true) String image,
			@RequestParam(value = "dir", required = false) String dir,
			@RequestParam(value = "thum_w", required = false) Integer width, HttpServletRequest req,
			HttpServletResponse resp) {

		// 只允许jpg
		String jpg = "data:image/jpeg;base64,";
		String png = "data:image/png;base64,";

		if (image.indexOf(jpg) == 0&&image.indexOf(png) == 0) {

			return new ResultCode<String>(5001,"文件格式有误,只允许jpg、png格式",null);
		}
		String header=image.contains(jpg)?jpg:png;
		// 去掉头部
		image = image.substring(header.length());
		 String fileURL=FileUtil.uploadFile(image, dir, width, req);
		if(fileURL==null)
			return new ResultCode<String>(5002, "上传文件失败", null);
		else 
			return new ResultCode<String>(fileURL);
	}
	@RequestMapping("/web-upload")
	@ResponseBody
	public ResultCode<String> webUploadFile(
			@RequestParam(value = "file", required = false)MultipartFile file,
			@RequestParam(value = "dir", required = false)String dir,
			HttpServletRequest request, HttpServletResponse response)  {
		Profile user=(Profile) request.getSession().getAttribute("user");

		if(10500000<=file.getSize()){
			return new ResultCode<String>(502,"文件过大",null);
		}
		
		String filename=file.getOriginalFilename();
		String suffix=filename.substring(filename.lastIndexOf('.'));
		String suffixItems=".jpg.gif.png.bmp.obj.brep.rar.zip";
		if(!suffixItems.contains(suffix)){
			return new ResultCode<String>(405,"暂时只支持STL,STP,IGS,OBJ,BREP,RAR,ZIP模型",null);
		}
		String img_url=null;
		try {
			img_url = FileUtil.uploadFile(file, dir, request,user.getName());
		} catch (IllegalStateException | IOException e) {
			log.error(e.getMessage());
		}
		if(ValidationUtil.isEmpty(img_url)){
			return new ResultCode<String>(5003,"创建文件写入数据失败",null);
		}
		return new ResultCode<String>(img_url);
	}	
	@RequestMapping("/web-upload-record")
	@ResponseBody
	public ResultCode<String> webUploadRecord(
			@RequestParam(value = "file", required = false)MultipartFile file,
			@RequestParam(value = "dir", required = false)String dir,
			HttpServletRequest request, HttpServletResponse response)  {
		Profile user=(Profile) request.getSession().getAttribute("user");

		if(10500000<=file.getSize()){
			return new ResultCode<String>(502,"文件过大",null);
		}
		
		String filename=file.getOriginalFilename();
		String suffix=filename.substring(filename.lastIndexOf('.'));
		//String suffixItems=".do.gif.png.bmp.obj.brep.rar.zip";
		/*if(!suffixItems.contains(suffix)){
			return new ResultCode<String>(405,"暂时只支持STL,STP,IGS,OBJ,BREP,RAR,ZIP模型",null);
		}*/
		String img_url=null;
		try {
			img_url = FileUtil.uploadFileExec(file, dir, request,user.getName());
		} catch (IllegalStateException | IOException e) {
			log.error(e.getMessage());
		}
		if(ValidationUtil.isEmpty(img_url)){
			return new ResultCode<String>(5003,"创建文件写入数据失败",null);
		}
		return new ResultCode<String>(img_url);
	}	
	
	/**
     * 文件下载
     * @Description: 
     * @param fileName
     * @param request
     * @param response
     * @return
	 * @throws UnsupportedEncodingException 
     */
    @RequestMapping("/download")
    public String downloadFile(@RequestParam("path") String path,HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
    		if (path == null || "".equals(path)) {
				return null;
			}// 文件名
        	String fileName = path.substring(path.lastIndexOf("/")+1);
        	// 文件真实路径
        	String  realpath=request.getSession().getServletContext().getRealPath("/");
        	//url路径
        	String basepath=RequestUtil.getBasePath(request);
        	
        	int index = path.indexOf(basepath);
        	
        	if (index  == -1) {
				return null;
			}
        	String filepath=path.substring(index+basepath.length()+1);
            File file = new File(realpath,filepath);
            if (file.exists()) {

                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        
        return null;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值