SpringMvc上传图片

SpringMvc上传图片,仅供参考,开发这么久第一次写博客,希望大家别喷,有不足之处希望大家多多指教。
Controller:
@ResponseBody @RequestMapping(params
= "uploadImge") public String uploadImge(HttpServletRequest request) { Map<String, List<List<String>>> map = new HashMap<>(); List<List<String>> newImgNames = new ArrayList<>(); //请求解析器 CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext()); String imgname = request.getParameter("imgname"); if(!StringUtil.isEmpty(imgname)){ String[] imgnameArr = imgname.split(","); for (int i = 0; i < imgnameArr.length; i++) { deleteImg(request, imgnameArr[i]); } } //判断是否有文件上传 if (cmr.isMultipart(request)) { //转换成MultipartHttpRequest MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request); //获取所有文件名的迭代器 Iterator<String> files = mRequest.getFileNames(); //拿到每一个文件 while (files.hasNext()) { //按照文件名称获取这个上传文件,上传文件被转化为MultipartFile 对象 MultipartFile mFile = mRequest.getFile(files.next()); if (mFile != null) { // String fileName = UUID.randomUUID() + mFile.getOriginalFilename(); newImgNames.add(saveFile(mFile, request)); } } map.put("fileMsg", newImgNames); } JSONArray arr = JSONArray.fromObject(map); System.out.println(arr); return arr.toString(); } /** * 保存图片 * * @param file * @param request * @return */ private List<String> saveFile(MultipartFile file, HttpServletRequest request) { List<String> list = new ArrayList<>(); try { byte[] bytes = file.getBytes(); // 当前项目根目录 String rootPath = request.getServletContext().getRealPath("/"); // 在当前项目中地址 String relativePath = "upload/app"; // 文件夹是否存在,不存在就创建 File dir = new File(rootPath + File.separator + relativePath); if (!dir.exists()) dir.mkdirs(); String fileExtension = FileUtils.getFileExtension(file); // String filename = file.getName(); //文件原名字 String uuid = java.util.UUID.randomUUID().toString() .replace("-", ""); long timeMillis = System.currentTimeMillis(); // 时间戳 // 图片名称 String fileName = uuid + timeMillis + "." + fileExtension; //访问图片路径 String fullServerPath = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath()).toString() +"/"+ relativePath +"/"+ fileName; // 图片在服务器的路径 String serverPath = dir.getAbsolutePath() + File.separator + fileName; // 保存图片 File serverFile = new File(serverPath); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); /*logger.info("Server File Location = " + serverFile.getAbsolutePath()); String serverPath = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath()).toString();*/ HFileUploadDownloadGaoEntity fileEntity = new HFileUploadDownloadGaoEntity(); fileEntity.setFileName(fileName); fileEntity.setFilePath(serverPath); fileEntity.setFileUploadTime(df.format(new Date())); systemService.save(fileEntity); list.add(fullServerPath); list.add(fileName); } catch (Exception e) { logger.info("error: {}", e); } return list; } /** * 删除图片在数据库中的路径 * @param request * @param imgName * @return */ @RequestMapping(params="deleteImg") @ResponseBody public int deleteImg(HttpServletRequest request,String imgName){ int result = -1; if (StringUtil.isEmpty(imgName)) { imgName = request.getParameter("imgName"); } HFileUploadDownloadGaoEntity entity = dao.getImgPath(imgName); String path = entity.getFilePath(); boolean delete = FileUtils.delete(path); if (delete) { result = dao.deleteImg(imgName); }else{ result = 0; } return result; }
package org.jeecgframework.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件操作工具类
 * @author 
 *
 */
public class FileUtils {
    
    /**
     * 获取文件扩展名
     * 
     * @param file
     * @return
     */
    public static String getFileExtension(MultipartFile file) {
        String fileName = file.getName();
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }
    
    /**
     * 获取文件扩展名
     * 
     * @param filename
     * @return
     */
    public static String getExtend(String filename) {
        return getExtend(filename, "");
    }

    /**
     * 获取文件扩展名
     * 
     * @param filename
     * @return
     */
    public static String getExtend(String filename, String defExt) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');

            if ((i > 0) && (i < (filename.length() - 1))) {
                return (filename.substring(i+1)).toLowerCase();
            }
        }
        return defExt.toLowerCase();
    }

    /**
     * 获取文件名称[不含后缀名]
     * 
     * @param
     * @return String
     */
    public static String getFilePrefix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(0, splitIndex).replaceAll("\\s*", "");
    }
    
    /**
     * 获取文件名称[不含后缀名]
     * 不去掉文件目录的空格
     * @param
     * @return String
     */
    public static String getFilePrefix2(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(0, splitIndex);
    }
    
    /**
     * 文件复制
     *方法摘要:这里一句话描述方法的用途
     *@param
     *@return void
     */
    public static void copyFile(String inputFile,String outputFile) throws FileNotFoundException{
        File sFile = new File(inputFile);
        File tFile = new File(outputFile);
        FileInputStream fis = new FileInputStream(sFile);
        FileOutputStream fos = new FileOutputStream(tFile);
        int temp = 0;  
        byte[] buf = new byte[10240];
        try {  
            while((temp = fis.read(buf))!=-1){   
                fos.write(buf, 0, temp);   
            }   
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally{
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 
    }
    /**
     * 判断文件是否为图片<br>
     * <br>
     * 
     * @param filename
     *            文件名<br>
     *            判断具体文件类型<br>
     * @return 检查后的结果<br>
     * @throws Exception
     */
    public static boolean isPicture(String filename) {
        // 文件名称为空的场合
        if (oConvertUtils.isEmpty(filename)) {
            // 返回不和合法
            return false;
        }
        // 获得文件后缀名
        //String tmpName = getExtend(filename);
        String tmpName = filename;
        // 声明图片后缀名数组
        String imgeArray[][] = { { "bmp", "0" }, { "dib", "1" },
                { "gif", "2" }, { "jfif", "3" }, { "jpe", "4" },
                { "jpeg", "5" }, { "jpg", "6" }, { "png", "7" },
                { "tif", "8" }, { "tiff", "9" }, { "ico", "10" } };
        // 遍历名称数组
        for (int i = 0; i < imgeArray.length; i++) {
            // 判断单个类型文件的场合
            if (imgeArray[i][0].equals(tmpName.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断文件是否为DWG<br>
     * <br>
     * 
     * @param filename
     *            文件名<br>
     *            判断具体文件类型<br>
     * @return 检查后的结果<br>
     * @throws Exception
     */
    public static boolean isDwg(String filename) {
        // 文件名称为空的场合
        if (oConvertUtils.isEmpty(filename)) {
            // 返回不和合法
            return false;
        }
        // 获得文件后缀名
        String tmpName = getExtend(filename);
        // 声明图片后缀名数组
        if (tmpName.equals("dwg")) {
            return true;
        }
        return false;
    }
    
    /**
     * 删除指定的文件
     * 
     * @param strFileName
     *            指定绝对路径的文件名
     * @return 如果删除成功true否则false
     */
    public static boolean delete(String strFileName) {
        File fileDelete = new File(strFileName);

        if (!fileDelete.exists() || !fileDelete.isFile()) {
            LogUtil.info("错误: " + strFileName + "不存在!");
            return false;
        }

        LogUtil.info("--------成功删除文件---------"+strFileName);
        return fileDelete.delete();
    }
    
    /**
     * 
    * @Title: encodingFileName 2015-11-26 huangzq add
    * @Description: 防止文件名中文乱码含有空格时%20 
    * @param @param fileName
    * @param @return    设定文件 
    * @return String    返回类型 
    * @throws
     */
    public static String encodingFileName(String fileName) {
        String returnFileName = "";
        try {
            returnFileName = URLEncoder.encode(fileName, "UTF-8");
            returnFileName = StringUtils.replace(returnFileName, "+", "%20");
            if (returnFileName.length() > 150) {
                returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
                returnFileName = StringUtils.replace(returnFileName, " ", "%20");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            LogUtil.info("Don't support this encoding ...");
        }
        return returnFileName;
    }
}

package com.towery.thermal.file.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecgframework.web.system.pojo.base.TSAttachment;

/**   
 * @Title: Entity
 * @Description: 文件上传实体类
 * @author onlineGenerator
 * @date 2017-10-12 11:05:55
 * @version V1.0   
 *
 */
@Entity
@Table(name = "h_file_upload_download_gao")
@PrimaryKeyJoinColumn(name = "id")
public class HFileUploadDownloadGaoEntity extends TSAttachment implements java.io.Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    /**主键*/
    // private java.lang.String id;
    /**创建人名称*/
    private java.lang.String createName;
    /**创建人登录名称*/
    private java.lang.String createBy;
    /**创建日期*/
    private java.util.Date createDate;
    /**更新人名称*/
    private java.lang.String updateName;
    /**更新人登录名称*/
    private java.lang.String updateBy;
    /**更新日期*/
    private java.util.Date updateDate;
    /**所属部门*/
    private java.lang.String sysOrgCode;
    /**所属公司*/
    private java.lang.String sysCompanyCode;
    /**流程状态*/
    private java.lang.String bpmStatus;
    /**文件名称*/
    private java.lang.String fileName;
    /**文件路径*/
    @Excel(name = "文件路径")
    private java.lang.String filePath;
    /**文件上传时间*/
    private java.lang.String fileUploadTime;
    /**模块外键*/
    private java.lang.String foreignKey;
    /**上传人*/
    private java.lang.String uploadPerson;

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  主键
     */
    // @Id
    // @GeneratedValue(generator = "paymentableGenerator")
    // @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
    // @Column(name = "ID", nullable = false, length = 36)
    // public java.lang.String getId() {
    // return this.id;
    // }
    //
    // /**
    // *方法: 设置java.lang.String
    // *@param: java.lang.String 主键
    // */
    // public void setId(java.lang.String id) {
    // this.id = id;
    // }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  创建人名称
     */
    @Column(name = "CREATE_NAME", nullable = true, length = 50)
    public java.lang.String getCreateName() {
        return this.createName;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  创建人名称
     */
    public void setCreateName(java.lang.String createName) {
        this.createName = createName;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  创建人登录名称
     */
    @Column(name = "CREATE_BY", nullable = true, length = 50)
    public java.lang.String getCreateBy() {
        return this.createBy;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  创建人登录名称
     */
    public void setCreateBy(java.lang.String createBy) {
        this.createBy = createBy;
    }

    /**
     *方法: 取得java.util.Date
     *@return: java.util.Date  创建日期
     */
    @Column(name = "CREATE_DATE", nullable = true, length = 20)
    public java.util.Date getCreateDate() {
        return this.createDate;
    }

    /**
     *方法: 设置java.util.Date
     *@param: java.util.Date  创建日期
     */
    public void setCreateDate(java.util.Date createDate) {
        this.createDate = createDate;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  更新人名称
     */
    @Column(name = "UPDATE_NAME", nullable = true, length = 50)
    public java.lang.String getUpdateName() {
        return this.updateName;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  更新人名称
     */
    public void setUpdateName(java.lang.String updateName) {
        this.updateName = updateName;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  更新人登录名称
     */
    @Column(name = "UPDATE_BY", nullable = true, length = 50)
    public java.lang.String getUpdateBy() {
        return this.updateBy;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  更新人登录名称
     */
    public void setUpdateBy(java.lang.String updateBy) {
        this.updateBy = updateBy;
    }

    /**
     *方法: 取得java.util.Date
     *@return: java.util.Date  更新日期
     */
    @Column(name = "UPDATE_DATE", nullable = true, length = 20)
    public java.util.Date getUpdateDate() {
        return this.updateDate;
    }

    /**
     *方法: 设置java.util.Date
     *@param: java.util.Date  更新日期
     */
    public void setUpdateDate(java.util.Date updateDate) {
        this.updateDate = updateDate;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  所属部门
     */
    @Column(name = "SYS_ORG_CODE", nullable = true, length = 50)
    public java.lang.String getSysOrgCode() {
        return this.sysOrgCode;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  所属部门
     */
    public void setSysOrgCode(java.lang.String sysOrgCode) {
        this.sysOrgCode = sysOrgCode;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  所属公司
     */
    @Column(name = "SYS_COMPANY_CODE", nullable = true, length = 50)
    public java.lang.String getSysCompanyCode() {
        return this.sysCompanyCode;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  所属公司
     */
    public void setSysCompanyCode(java.lang.String sysCompanyCode) {
        this.sysCompanyCode = sysCompanyCode;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  流程状态
     */
    @Column(name = "BPM_STATUS", nullable = true, length = 32)
    public java.lang.String getBpmStatus() {
        return this.bpmStatus;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  流程状态
     */
    public void setBpmStatus(java.lang.String bpmStatus) {
        this.bpmStatus = bpmStatus;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  文件名称
     */
    @Column(name = "FILE_NAME", nullable = true, length = 200)
    public java.lang.String getFileName() {
        if (fileName != null) {
            String fileName_ = fileName.replace(" ", "");
            return fileName_;
        } else {
            return this.fileName;
        }
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  文件名称
     */
    public void setFileName(java.lang.String fileName) {
        this.fileName = fileName;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  文件路径
     */
    @Column(name = "FILE_PATH", nullable = true, length = 200)
    public java.lang.String getFilePath() {
        return this.filePath;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  文件路径
     */
    public void setFilePath(java.lang.String filePath) {
        this.filePath = filePath;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  文件上传时间
     */
    @Column(name = "FILE_UPLOAD_TIME", nullable = true, length = 100)
    public java.lang.String getFileUploadTime() {
        return this.fileUploadTime;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  文件上传时间
     */
    public void setFileUploadTime(java.lang.String fileUploadTime) {
        this.fileUploadTime = fileUploadTime;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  模块外键
     */
    @Column(name = "FOREIGN_KEY", nullable = true, length = 64)
    public java.lang.String getForeignKey() {
        return this.foreignKey;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  模块外键
     */
    public void setForeignKey(java.lang.String foreignKey) {
        this.foreignKey = foreignKey;
    }

    /**
     *方法: 取得java.lang.String
     *@return: java.lang.String  上传人
     */
    @Column(name = "UPLOAD_PERSON", nullable = true, length = 64)
    public java.lang.String getUploadPerson() {
        return this.uploadPerson;
    }

    /**
     *方法: 设置java.lang.String
     *@param: java.lang.String  上传人
     */
    public void setUploadPerson(java.lang.String uploadPerson) {
        this.uploadPerson = uploadPerson;
    }
}

 


 

posted @ 2018-01-09 18:00  谱写自己的人生  阅读(278)  评论(0编辑  收藏  举报