zoukankan      html  css  js  c++  java
  • resteay上传单个文件/多个文件到本地

    代码如下:


    CADLocalControlle.java
    package com.xgt.controller;
    
    import com.xgt.common.BaseController;
    import com.xgt.common.PcsResult;
    import com.xgt.service.bs.ExcelService;
    import com.xgt.util.MD5Util;
    import org.apache.commons.io.IOUtils;
    import org.jboss.resteasy.plugins.providers.multipart.InputPart;
    import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    
    import javax.ws.rs.Consumes;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.MultivaluedMap;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    import java.util.Map;
    
    /**
     * Created by Administrator on 2017/8/28.
     * 上传Excel到本地
     */
    @Controller
    @Path("/cadlocal")
    public class CADLocalController extends BaseController{
        @Autowired
        private ExcelService excelService;
    
    
        private final String UPLOADED_FILE_PATH = "e:\upload\";
        @POST
        @Path("/uploadLocalCAD")
        @Consumes(MediaType.MULTIPART_FORM_DATA )
        @Produces(MediaType.APPLICATION_JSON)
        //@RequiresPermissions("picturelocal:uploadPicture")
        public PcsResult uploadFile(MultipartFormDataInput input) {
            String fileName = "";
            Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
            List<InputPart> inputParts = uploadForm.get("fileselect[]");
            for (InputPart inputPart : inputParts) {
                try {
                    MultivaluedMap<String, String> header = inputPart.getHeaders();
                    fileName = getFileName(header);
                    fileName = MD5Util.MD5(fileName+System.currentTimeMillis());
                    fileName = fileName+".dwg";
                    //convert the uploaded file to inputstream
                    InputStream inputStream = inputPart.getBody(InputStream.class,null);
                    byte [] bytes = IOUtils.toByteArray(inputStream);
                    //constructs upload file path
                    fileName = UPLOADED_FILE_PATH + fileName;
                    writeFile(bytes,fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return newResult(true);
    
        }
    
        private String getFileName(MultivaluedMap<String, String> header) {
            String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
            for (String filename : contentDisposition) {
                if ((filename.trim().startsWith("filename"))) {
                    String[] name = filename.split("=");
                    String finalFileName = name[1].trim().replaceAll(""", "");
                    return finalFileName;
                }
            }
            return "unknown";
        }
    
        //save to somewhere
        private void writeFile(byte[] content, String filename) throws IOException {
            File file = new File(filename);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fop = new FileOutputStream(file);
            fop.write(content);
            fop.flush();
            fop.close();
        }
    }

    BaseController.java

    package com.xgt.common;
    
    import com.xgt.dao.entity.User;
    import com.xgt.exception.EnumPcsServiceError;
    import org.apache.shiro.SecurityUtils;
    import org.springframework.beans.factory.annotation.Value;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import java.util.List;
    
    /**
     * Base controller which contains common methods for other controllers.
     */
    public class BaseController {
    
        @Value("${default.pageSize}")
        private int defPageSize;
    
    
        @Value("${default.maxPageSize}")
        private int defMaxPageSize;
    
    
        @Value("${aliyunOSS.accessKeyId}")
        protected String accessKeyId;
    
        @Value("${aliyunOSS.accessKeySecret}")
        protected String accessKeySecret;
    
        @Value("${aliyunOSS.uploadUrl}")
        protected String endpoint;
    
        @Value("${aliyunOSS.bucketname}")
        protected String bucketName;
    
        @Value("${aliyunOSS.imageAddress}")
        protected String imageAddress;
    
        /**
         * Generate new PcsResult object, default with "SUCCESS" code.
         *
         * @return PcsResult result.
         */
        protected PcsResult newResult() {
            PcsResult result = new PcsResult();
            result.setCode(EnumPcsServiceError.SUCCESS.getCode()).setMessage(EnumPcsServiceError.SUCCESS.getDesc());
            return result;
        }
        /**
         * Generate new PcsResult object, default with "SUCCESS" code.
         *
         * @return PcsResult result.
         */
        protected PcsResult newResult(Boolean success) {
            PcsResult result = new PcsResult();
            result.setSuccess(success);
            result.setCode(EnumPcsServiceError.SUCCESS.getCode()).setMessage(EnumPcsServiceError.SUCCESS.getDesc());
    
            return result;
        }
    
    
        protected PcsResult failedResult(EnumPcsServiceError error) {
            PcsResult result = new PcsResult();
            result.setCode(error.getCode()).setMessage(error.getDesc());
            return result;
        }
    
        @SuppressWarnings("unused")
        protected PcsResult validateFailedResult(Integer errorCode, String description) {
            PcsResult result = new PcsResult();
            result.setCode(errorCode).setMessage(description);
            return result;
        }
    
        @SuppressWarnings("unused")
        protected PcsResult validateFailedResult(EnumPcsServiceError error) {
            PcsResult result = new PcsResult();
            result.setCode(error.getCode()).setMessage(error.getDesc());
            return result;
        }
    
        protected Integer getLoginUserId(){
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            return user.getUserId();
        }
    
        protected List<Integer> getDepartmentUserIdList(){
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            return user.getDepartmentUserIdList();
        }
    
    
        /**
         * 构建 分页 页数
         * @param page 页
         * @return int
         */
        protected int getCurPage(Integer page) {
            if (page==null || page<1) {
                return 1;
            }
            return page;
        }
        /**
         * 构建 分页 每页显示条数
         * @param pageSize 每页显示条数
         * @return int
         */
        protected int getPageSize(Integer pageSize) {
            if (pageSize==null || pageSize<1) {
                return defPageSize;
            }
            if (pageSize>defMaxPageSize) {
                return defMaxPageSize;
            }
            return pageSize;
        }
    
    }

    补充说明:

    for (InputPart inputPart : inputParts) {}用于获得接收到的文件,可以接收多文件
    fileName = MD5Util.MD5(fileName+System.currentTimeMillis());这里把文件名用MD5算法加密,不是为了加密,而是我在流中获取的中文文件名乱码,还没想好解决方案
    fileName = fileName+".dwg";这里上传的是CAD文件,拼接后缀dwg
  • 相关阅读:
    2010.10.10 第九课 函数(二)(递归)(汉诺塔)
    2020.10.8第八课函数(一)(4种函数)
    2020.9.29 第七课 字符串函数与字符数组
    2020.9.26第六节课数组
    2020.9.22 第四课 运算符表达式和语句
    2020.9.19 第三课 字符串格式化输出与输入
    2020.9.17 第二课 C语言中数据类型 2,8,10进制转换 计算机内存数值存储方式(补码转换)
    2020.9.15 第一课,概念
    spring架构解析--入门(一)
    JAVA对象实例化方式总结
  • 原文地址:https://www.cnblogs.com/Java-Starter/p/7495670.html
Copyright © 2011-2022 走看看