java 后台 文件上传接口

本接口是后台接口 本文没有ajax请求  还需要其他的jar包 代码仅供参考

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.centit.cmip.app.common.dao.DefaultDao;
import com.centit.cmip.biz.common.util.MD5Util;
import com.centit.cmip.biz.common.util.Office2PDF;
import com.centit.cmip.biz.nhmain.entity.response.CommonResponseFileBean;
import com.centit.cmip.biz.nhmain.utils.MapperUtils;
import com.centit.cmip.framework.action.BaseAction;
import com.centit.cmip.sdk.common.utils.DateUtil;
import com.centit.cmip.util.PrivateKeyUtil;
import com.centit.cmip.webapp.assetmgr.entity.AssetEntity;
import com.centit.cmip.webapp.assetmgr.service.AssetService;
import com.centit.cmip.webapp.privatekey.entity.TableEnum;
import com.mysql.fabric.xmlrpc.base.Array;

import net.sf.json.JSONObject;


@Controller("dduploadAction")
@Scope("prototype")
public class DDUploadAction extends BaseAction {
    
    private static final long serialVersionUID = 2358985464071330705L;
    
    private static Logger logger = Logger.getLogger(DDUploadAction.class);
    
    private AssetEntity asset;
    
    @Value("${upload.filedir}")
    private String uploadDir;
    @Value("${image.prefix}")
    private String imagePrefix;
    @Value("${filepush.url}")
    private String filepushUrl;//文件转发目标服务器地址
    
    @Value("${filepush.switch}")
    private String filepushSwitch;//文件转发开关
    
    @Value("${persistence.type}")
    private String persistenceType;//持久化类型
    
    @Resource
    private AssetService assetService;
    @Resource
    private PrivateKeyUtil privateKeyUtil;
    @Resource
    private Office2PDF office2PDF;
    @Resource
    private DefaultDao defaultDao;
    
    private File imgFile;
    
    private String imgFileFileName;
    
    @PostConstruct
    public void init() {
        if (null == asset) {
            asset = new AssetEntity();
        }
    }
    
    /**
     * description:图片上传
     * description: 也可根据文件流上传文件,此处会读取
     *              request中的文件流,如果页面控件是File上传,此方法不一定适用可用
     *              receive1()方法上传
     * @author 
     * @date 2018-12-25 9:31:00            
     */
    public void receive() {
        try {
            if ("db".equals(persistenceType)) {
                save2DB(getRequest().getInputStream(),getRequest().getParameter("name"),getRequest().getParameter("code"));
            } else if ("disk".equals(persistenceType)) {
                //String name = new String(getRequest().getParameter("name").getBytes("iso-8859-1"), "utf-8");
                String name = getRequest().getParameter("name");
                save2Disk(getRequest().getInputStream(), name,getRequest().getParameter("code"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * description: 文件上传
     * @param File imgFile 文件上传,需要根据File对象创建文件流再进行上传
     * @param String imgFileFileName 文件真实名称,
     *        request.getParamMeter("name")根据客户端控件的不同可能上传的是文件临时文件名称,非文件真实名称
     * @author xu_xl
     * @date 2018-12-25 9:31:00
     */
    public void receive2() {
        try {
            FileInputStream inputStream = new FileInputStream(imgFile);
            //String name = new String(getRequest().getParameter("name").getBytes("iso-8859-1"), "utf-8");
            String name = getRequest().getParameter("name");
            String code = getRequest().getParameter("code");
            String fileTyle=name.substring(name.lastIndexOf("."),name.length());// 获取文件的扩展名,比如 .gif
            //根据code获取字典值名 进行重命名
            HashMap<String, Object> hMap = new HashMap<String, Object>();
            hMap.put("code",code);
            String codename="";
            @SuppressWarnings("unchecked")
            List<CommonResponseFileBean> list=(List<CommonResponseFileBean>)defaultDao.queryForList("selectfileName", hMap);
            for(CommonResponseFileBean bean:list) {
                codename = bean.getFileName();
            }
            String newname = codename +fileTyle;
            if(StringUtils.isNotBlank(imgFileFileName)) {
                name = imgFileFileName;
            }
            //调用文件保存方法
            if ("db".equals(persistenceType)) {
                save2DB(inputStream,newname,code);
            } else if ("disk".equals(persistenceType)) {
                save2Disk(inputStream, newname,code);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * description: 后台接收文件
     * @throws UnsupportedEncodingException
     * @author 原有方法
     * @date 
     */
    public void receiveOnlyPdf() throws UnsupportedEncodingException{
        String fileName = getRequest().getParameter("name");
        InputStream inputStream = null;
        try {
            inputStream = getRequest().getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if(fileName.lastIndexOf("doc")>0||fileName.lastIndexOf("docx")>0){
            String storePath = "/resource/upload/" + DateUtil.current("yyyy-MM-dd")+"/" +fileName;
            String tempPath = uploadDir + storePath;
            File file = new File(tempPath);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            try {
                writeIntoOut(inputStream,new FileOutputStream(file));
                String office2pdf2 = office2PDF.office2PDF(tempPath);
                inputStream = new FileInputStream(new File(office2pdf2));
                fileName = fileName.substring(0,fileName.lastIndexOf(".")) + ".pdf";
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
        }
        
        if("db".equals(persistenceType)){
            save2DB(inputStream,fileName,getRequest().getParameter("code"));
        }else if("disk".equals(persistenceType)){
            save2Disk(inputStream,fileName,getRequest().getParameter("code"));
        }
    }
    
    /**
     * description:上传文件保存到数据库
     * @param inputSream
     * @param fileName
     * @author 原有方法
     * @date 
     */
    private void save2DB(InputStream inputSream,String fileName,String code){
        String realFile = null;
        HashMap<String,Object> ret = new HashMap<String,Object>();
        try {
            String fileSize = getRequest().getParameter("size");
            String fileType = getRequest().getParameter("type");
            String uid = getRequest().getParameter("uid");
            if(fileName.length()>60){
                ret.put("ret", false);
                ret.put("retMsg", "上传文件名过长,不可大于60");
                this.getResponse().getWriter().write(JSONObject.fromObject(ret).toString());
                return;
            }
            String assetId = privateKeyUtil.getPK(TableEnum.T_OM_ASSET);
            asset.setId(assetId);
            asset.setName(fileName);
            asset.setFileSize(fileSize);
            asset.setFileType(fileType);
            asset.setToken(MD5Util.md5("" + (assetId +System.currentTimeMillis()))); 
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            writeIntoOut(inputSream,byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            asset.setFileContent(byteArray);
            assetService.saveAssetEntity(asset);
            ret.put("ret", true);
            ret.put("assetid", assetId);
            ret.put("code", code);
            ret.put("name", asset.getName());
            ret.put("uid", uid);
            this.getResponse().getWriter().write(JSONObject.fromObject(ret).toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        if("on".equals(filepushSwitch)){
            this.relay(fileName, realFile, filepushUrl);
        }
    
    }
    
    /**
     * description:上传文件保存到硬盘
     * @param inputStream
     * @param fileName
     * @author 原有方法
     * @date 
     */
    private void save2Disk(InputStream inputStream,String fileName,String code){
        // 文件上传与返回值存在跨域问题,以下代码是为了解决响应跨域问题
        HttpServletRequest request = getRequest();
        String origin = request.getHeader("Origin");
        HttpServletResponse response = getResponse();
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
                
        InputStream is = null;
        String realFile = null;
        HashMap<String,Object> ret = new HashMap<String,Object>();
        try {
            String fileSize = request.getParameter("size");
            String fileType = request.getParameter("type");
            String uid = request.getParameter("uid");
            if(fileName.length()>60){
                ret.put("ret", false);
                ret.put("retMsg", "上传文件名过长,不可大于60");
                this.getResponse().getWriter().write(JSONObject.fromObject(ret).toString());
                return;
            }
            //String assetId = privateKeyUtil.getPK(TableEnum.T_OM_ASSET);
            String assetId = UUID.randomUUID().toString().replace("-", "");
            asset.setId(assetId);
            asset.setName(fileName);
            asset.setFileSize(fileSize);
            asset.setFileType(fileType);
            asset.setToken(MD5Util.md5("" + (assetId +System.currentTimeMillis()))); 
            fileName = assetId + fileName.substring(fileName.lastIndexOf("."));
            String storePath = "/resource/upload/" + DateUtil.current("yyyy-MM-dd")+"/" +fileName;
            realFile = uploadDir + storePath;
            asset.setStorePath(storePath);
            File file = new File(realFile);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            is = request.getInputStream();
            writeIntoOut(inputStream,new FileOutputStream(file));
            assetService.saveAssetEntity(asset);
            ret.put("ret", true);
            ret.put("assetid", assetId);
            ret.put("code", code);
            ret.put("name", asset.getName());
            ret.put("uid", uid);
            ret.put("url", imagePrefix+storePath);
            //判断request请求方法
            String method = request.getMethod();
            if(method.equalsIgnoreCase("OPTIONS"))
                response.getOutputStream().write(JSONObject.fromObject(ret).toString().getBytes("utf-8"));
            else
                response.getWriter().write(JSONObject.fromObject(ret).toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if("on".equals(filepushSwitch)){
            this.relay(fileName, realFile, filepushUrl);
        }
    }
    
    /**
     * 
     * @param fileName 保存文件名
     * @param filePath 保存本地的文件路径
     * @param url 目标服务器的地址
     */
    public void relay(String fileName,String filePath,String url){
        url = url+"?name="+fileName +"&uploadDir="+uploadDir;
        
        //文件转发
        byte[] buffer = this.File2byte(filePath);
        
        StringBuilder sb2 = null;
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";

        URL uri = null;
        try {
            uri = new URL(url);
            HttpURLConnection conn= null;
            try {
                conn = (HttpURLConnection) uri.openConnection();
                conn.setReadTimeout(60 * 1000); // 缓存的最长时间
                conn.setDoInput(true);// 允许输入
                conn.setDoOutput(true);// 允许输出
                conn.setUseCaches(false); // 不允许使用缓存
                conn.setRequestMethod("POST");
                conn.setRequestProperty("connection", "keep-alive");
                conn.setRequestProperty("Charsert", "UTF-8");
                conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
                
                DataOutputStream outStream;
                outStream = new DataOutputStream(conn.getOutputStream());
                InputStream in = null;
                
                // 发送文件数据
                outStream.write(buffer);
                // 得到响应码
                int res = conn.getResponseCode();
                if (res == 200){
                    in = conn.getInputStream();
                    int ch;
                    sb2 = new StringBuilder();
                    while ((ch = in.read()) != -1){
                        sb2.append((char) ch);
                    }
                }
                outStream.close();
                conn.disconnect();
                
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * description:后台发送文件
     */
    public void send(){
        if("db".equals(persistenceType)){
            sendByDB();
        }else if("disk".equals(persistenceType)){
            sendByDisk();
        }
    
    }
    
    public void sends(){
        if("db".equals(persistenceType)){
            sendByDB();
        }else if("disk".equals(persistenceType)){
            sendByDisks();
        }
    
    }
    
    private void sendByDB(){

        try {
            String assetId = getRequest().getParameter("id");
            asset.setId(assetId);
            asset = assetService.queryOne(asset);
            if (asset.getFileContent() != null) {
                getResponse().setContentType(asset.getFileType());
                getResponse().setHeader("Content-Disposition","attachment; filename="+new String((asset.getName()).getBytes("gbk"), "iso-8859-1"));
                ByteArrayInputStream is = new ByteArrayInputStream(asset.getFileContent());
                writeIntoOut(is, getResponse().getOutputStream());
            } else {
                getResponse().sendError(404);
            }
        } catch (Exception e) {
            logger.error("未找到文件!");
        } 
    
    }
    
    private void sendByDisk(){
        try {
            String assetId = getRequest().getParameter("id");
            asset.setId(assetId);
            asset = assetService.queryOne(asset);
            asset.setId(assetId);
            asset = assetService.queryOne(asset);
            File ff;
            String[] strs=asset.getStorePath().split("&\\^&");
            if(strs.length>=2){
                ff = new File(uploadDir + strs[1]);
            }else{
                ff = new File(uploadDir + asset.getStorePath());
            }
            if (ff.exists()) {
                getResponse().setContentType(asset.getFileType());
                getResponse().setHeader("Content-Disposition","attachment; filename="+new String((asset.getName()).getBytes("gbk"), "iso-8859-1"));
                FileInputStream fins = new FileInputStream(ff);
                writeIntoOut(fins, getResponse().getOutputStream());
            } else {
                getResponse().sendError(404);
            }
        } catch (Exception e) {
            logger.error("未找到文件!");
        } 
    }
    
    
    private void sendByDisks(){
        try {
            String assetId = getRequest().getParameter("id");
            asset.setId(assetId);
            asset = assetService.queryOne(asset);
            String[] strs=asset.getStorePath().split("&\\^&");
            File ff = new File(uploadDir + strs[0]);
            if (ff.exists()) {
                getResponse().setContentType(asset.getFileType());
                getResponse().setHeader("Content-Disposition","attachment; filename="+new String((asset.getName()).getBytes("gbk"), "iso-8859-1"));
                FileInputStream fins = new FileInputStream(ff);
                writeIntoOut(fins, getResponse().getOutputStream());
            } else {
                getResponse().sendError(404);
            }
        } catch (Exception e) {
            logger.error("未找到文件!");
        } 
    }
    
    private void writeIntoOut(InputStream ins, OutputStream out) {
        byte[] bb = new byte[10 * 1024];
        try {
            int cnt = ins.read(bb);
            while (cnt > 0) {
                out.write(bb, 0, cnt);
                cnt = ins.read(bb);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ins.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    
    public static byte[] File2byte(String filePath)  
    {  
        byte[] buffer = null;  
        try  
        {  
            File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] b = new byte[1024];  
            int n;  
            while ((n = fis.read(b)) != -1)  
            {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        }  
        catch (FileNotFoundException e)  
        {  
            e.printStackTrace();  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        return buffer;  
    }
    
    //富文本图片上传
    public void uploadImgByKindeditor() throws IOException, FileUploadException{
        PrintWriter out =getResponse().getWriter();
        //String androidpublishurl=smConfigService.AndroidPublishUrl();
        String DateDir = DateUtil.current("yyyy-MM-dd") + "/";
        String savePath = uploadDir + "/resource/upload/" + DateDir ;
        
        File saveDir = new File(savePath);
        if (!saveDir.exists()){
            saveDir.mkdirs();
        }

        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        //最大文件大小 100M
        long maxSize = 100000000;

        getResponse().setContentType("text/html; charset=UTF-8");

        if(!ServletFileUpload.isMultipartContent(getRequest())){
            out.println(getError("请选择文件。"));
            return;
        }
        //检查目录
        File uploadDir = new File(savePath);
        if(!uploadDir.isDirectory()){
            out.println(getError("上传目录不存在。"));
            return;
        }
        //检查目录写权限
        if(!uploadDir.canWrite()){
            out.println(getError("上传目录没有写权限。"));
            return;
        }
        
        //检查文件大小
        if(imgFile.length() > maxSize){
            out.println(getError("上传文件大小超过限制。"));
            return;
        }
        //检查扩展名
        String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();
        if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
            out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("image") + "格式。"));
            return;
        }
        imgFileFileName =  new Date().getTime() + "." + fileExt;
        String storePath = "/resource/upload/" + DateDir + imgFileFileName;
        writeIntoOut(new FileInputStream(imgFile.getAbsolutePath()),new FileOutputStream(new File(uploadDir + storePath)));
        
        String assetId = privateKeyUtil.getPK(TableEnum.T_OM_ASSET);            
        asset.setId(assetId);
        asset.setName(imgFileFileName);
        asset.setFileSize(String.valueOf(imgFile.length()));
        asset.setFileType(fileExt);
        asset.setToken(MD5Util.md5("" + (assetId +System.currentTimeMillis()))); 
        asset.setStorePath(storePath);
        assetService.saveAssetEntity(asset);
        JSONObject obj = new JSONObject();
        obj.put("error", 0);
        obj.put("url",imagePrefix + storePath);
        out.println(obj.toString());
        
    }
    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toString();
    }
    public File getImgFile() {
        return imgFile;
    }

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public String getImgFileFileName() {
        return imgFileFileName;
    }

    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }

}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值