• Java之xlsx文件上传到服务器


    package com.st.webadmin.bl;
    
    import com.st.baseutil.FileHelper;
    import com.st.baseutil.StringUtil;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.util.FileCopyUtils;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    
    import javax.servlet.http.HttpServletRequest;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.Map;
    import java.util.UUID;
    
    @Component
    public class UploadHelper {
    
        @Value("${fileserver.physical.location}")
        public String physicalPath;
        @Value("${fileserver.httpPreffix}")
        public String httpPreffix;
    
        public  String getPhysicalPath(String from, String sub) {
            String dirPath =physicalPath + from;
            FileHelper.createDir(dirPath);
            dirPath = dirPath + "/" + sub + "/";
            FileHelper.createDir(dirPath);
            return dirPath;
        }
    
        public  String upload(HttpServletRequest request, String pathPhysical, String url) throws Exception {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
            /*if (fileMap.size() == 0) throw new Exception("未找到上传的图片");*/
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileName = "";
            MultipartFile multipartFile = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                multipartFile = entity.getValue();
    
                fileName = multipartFile.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                fileName = uuid + suffix.toLowerCase();
                break;
            }
            File newFile = new File(pathPhysical + fileName);
            FileCopyUtils.copy(multipartFile.getBytes(), newFile);
            BufferedImage sourceImg = javax.imageio.ImageIO.read(newFile);
            /*int img_width = sourceImg.getWidth();
            int img_height = sourceImg.getHeight();*/
            /*if ((height + width) != 0 && (img_width != width || img_height != height)) {
                throw new Exception("上传失败,上传图片大小(width*height):" + img_width + "*" + img_height);
            }*/
            url=url+fileName;
            return url;
        }
    
        public  String getUrl(String from, String sub) {
            if (!StringUtil.isEmpty(sub))
                return httpPreffix + from + "/" + sub + "/";
            return httpPreffix + from + "/";
        }
    }
    

      编写一个文件上传类,配置相关路径地址。

    fileserver.physical.location=D:/projects/importTemplate/
    fileserver.httpPreffix=http://121.196.54.29:8017/
    

      application.properties配置路径

    @RequestMapping(value = "import", method = RequestMethod.POST)
        public String importFile(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response, @RequestParam("ImportExcelFile") MultipartFile upFile) throws IOException {
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            SysImportQueue importQueue = new SysImportQueue();
            importQueue.setName("导入客户资料");
            importQueue.setStatus(0); //0 处理中 1 成功 2 失败
            importQueue.setCreatedId(user.getId());
            importQueue.setCreatedOn(new Date());
            importQueue.setCreatedBy(user.getUserName());
            try {
                String pathPhysical = uploadHelper.getPhysicalPath("import", "memeber");
                String url = uploadHelper.getUrl("import", "memeber");
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String fileName = upFile.getOriginalFilename();
                importQueue.setFileName(fileName);
                String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                fileName = uuid + suffix.toLowerCase();
                File newFile = new File(pathPhysical + fileName);
                FileCopyUtils.copy(upFile.getBytes(), newFile);
                url=url+fileName;
                importQueue.setFileUrl(url);
                sysImportQueueService.insert(importQueue);
    
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return "appmember/import";
        }

      相关Controller方法

    <form class="form-inline" action="/appMember/import" id="importForm" name="importForm"
                                      method="post" enctype="multipart/form-data">
                                    <div class="form-body">
                                        <div class="form-group">
                                            <label class="control-label">选择需要上传的文件:</label>
                                            <input type="text" name="upfile" id="upfile" class="form-control"
                                                   style=" 500px;">
                                            <input type="button" value="浏览..." onclick="ImportExcelFile.click()"
                                                   class="btn btn-default">
                                            <input type="file" id="ImportExcelFile" name="ImportExcelFile"
                                                   style="display:none" onchange="upfile.value=this.value">
                                            <input type="button" class="btn  blue-chambray" value="上传"
                                                   onclick="submit()"/>
                                        </div>
                                    </div>
                                </form>

      就可以了

  • 相关阅读:
    Linux用户空间与内核地址空间
    [Linux内存]——内核地址空间
    使用 GDB 调试多进程程序
    Linux GDB常用命令
    GDB常用命令使用
    GDB调试原理——ptrace系统调用
    不可见乱码 怎么消除
    Vue use的理解
    Element-UI 下边框,表格错位问题
    sort 排序传递更多参数
  • 原文地址:https://www.cnblogs.com/Ifyou/p/14231213.html
Copyright © 2020-2023  润新知