码迷,mamicode.com
首页 > 编程语言 > 详细

Java上传图片

时间:2020-06-22 12:24:38      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:har   附件   指定   res   ror   default   content   文件写入   jmm   

直接上代码了。从一个功能摘取出来的,只保留了上传图片、附件的功能

1,上传图片按钮,样式需要调整。

<el-form :label-position="labelPosition" label-width="140px" :model="formLabelAlign" :rules="rules" ref="ruleForm" 
   name="upfile" id="insertbid" enctype="multipart/form-data">
  <el-form-item label="图片上传(限30M)"  id="juese">
     <input  type="file"name="file" id="cgqd"    placeholder="上传" onchange="fileChange(this);" >
     <label for="cgqd" style=" height: 52px; border: 1px solid #CCCCCC;width: 100%;position: absolute;top: 0;color: #ccc;line-height: 52px;border-radius: 4px;text-indent: 1rem">
       <span v-if="imgishows"><i class="glyphicon glyphicon-paperclip"></i>点击上传附件</span>
       <span v-if="!imgishows" style="color: #B0B0B0;">{{filenames}}</span>
     </label>
      <p  class="zhichige">支持格式: jpg,png,JPG,PNG</p>
  </el-form-item>
  <el-button type="danger" id="fabu_s" onclick="insert()" >提交</el-button>
</el-form>

2,js代码,使用Vue

function insert(){

var form = new FormData($("#insertbid")[0]);//获取表单

$.ajax({
url:"",
type:"POST",
dataType:"text",
data:form,
mimeType:"multipart/form-data",
contentType: false,
processData: false,
success:function(data){

if(data === "SUCCESS"){
alert("上传成功")
}else{
alert("上传失败")
}
},
})
}
$(‘#cgqd‘).change(function(){
if($("#cgqd")[0].files.length > 0) {
app.imgishows = false;
app.filenames = $("#cgqd")[0].files[0].name
}

});

/*
上传文件格式限制*/ function fileChange(target,id) { var filetypes =[".jpg",".png",".JPG",".PNG"]; var filepath = target.value; if(filepath){ var isnext = false; var fileend = filepath.substring(filepath.lastIndexOf(‘.‘)); if(filetypes && filetypes.length>0){ for(var i =0; i<filetypes.length;i++){ if(filetypes[i]==fileend){ isnext = true; break; } } } if(!isnext){ alert("不接受此文件类型!"); target.value =""; return false; } }else{ return false; } }

3,controller

    @RequestMapping("/insert")
    @ResponseBody
    public String projectInsert(HttpServletRequest request, MultipartFile file){
        String result = "";

        Project project = new Project();

        String fileNo = UUID.randomUUID().toString().replaceAll("-", "");//图片编号
        project.setImage(fileNo);
        FileInputUtil.addFile(purchaseSimpleNoticeService,file,fileNo);//上传图片,参数1:上传图片service接口,参数2:接收的图片,参数3:图片编号
        Integer num = iProjectService.projectInsert(project);
        if(num>0){
            result = "SUCCESS";
        }else{
            result = "ERROR";
        }
        return result;
    }

4,图片上传工具类

package cn.ljs.util;

import cn.ljs.entity.NoticeFile;
import cn.ljs.service.PurchaseSimpleNoticeService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 图片上传工具类
 * 
 * @author Thinkpad
 *
 */
public class FileInputUtil {

    /**
     * 图片上传
     * @param purchaseSimpleNoticeService
     * @param file
     */
    public static void addFile(PurchaseSimpleNoticeService purchaseSimpleNoticeService, MultipartFile file,
            String fileNo) {
        // 保存附件,未指定盘时一般为电脑的最后一个盘
        String realUploadPath = "/image/file";
        // 建立以时间命名的文件夹
        SimpleDateFormat sdf1 = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf1.format(new Date());
        // 最终真实路径
        String realuUploadBrandPath = realUploadPath + "/doc" + datePath;

        String jcfileName = file.getOriginalFilename();
        String jc = null;
        String alljc = null;
        if (jcfileName.contains("\\[") && jcfileName.contains("\\]")) {
            jc = jcfileName.replaceAll("\\[", "【");
            alljc = jc.replace("\\]", "】");
        } else {
            alljc = jcfileName;
        }
        // 上传文件原始名称
        String jcoriginFileName = new Date().getTime() + "_" + alljc;
        String jcaddress = "/doc" + datePath + jcoriginFileName;

        // 如果路径文件夹不存在就创建
        File dir = new File(realuUploadBrandPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 新文件
        File jcFile = new File(realuUploadBrandPath + File.separator + jcoriginFileName);
        if (file.getSize() != 0) {
            // 将内存中的文件写入磁盘
            try {
                file.transferTo(jcFile);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        if (file.getSize() != 0) {
            NoticeFile noticeFile = new NoticeFile();
            noticeFile.setBatch_no(fileNo);
            noticeFile.setAddress(jcaddress);
            noticeFile.setCreate_time(new Date());
            noticeFile.setName(alljc);
            String suffix = alljc.substring(alljc.length() - 4, alljc.length());
            noticeFile.setSuffix(suffix);
            purchaseSimpleNoticeService.addFlie(noticeFile);
        }
    }

    /**
     * 附件修改
     * @param purchaseSimpleNoticeService
     * @param file
     */
    public static void updateFile(PurchaseSimpleNoticeService purchaseSimpleNoticeService,
            MultipartFile file, String fileNo) {
        // 保存附件
        String realUploadPath = "/fphome/sotcbb/webapps/gzfppt/file";
        // 建立以时间命名的文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        // 最终真实路径
        String realuUploadBrandPath = realUploadPath + "/doc" + datePath;
        if (file.getSize() != 0) {
            String jcfileName = file.getOriginalFilename();
            String jc = null;
            String alljc = null;
            if (jcfileName.contains("\\[") && jcfileName.contains("\\]")) {
                jc = jcfileName.replaceAll("\\[", "【");
                alljc = jc.replace("\\]", "】");
            } else {
                alljc = jcfileName;
            }
            // 上传文件原始名称
            String jcoriginFileName = new Date().getTime() + "_" + alljc;
            String jcaddress = "/doc" + datePath + jcoriginFileName;
            // 如果路径文件夹不存在就创建
            File dir = new File(realuUploadBrandPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 新文件
            File jcFile = new File(realuUploadBrandPath + File.separator + jcoriginFileName);
            // 将内存中的文件写入磁盘
            try {
                file.transferTo(jcFile);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }

            String batch_no = fileNo;
            NoticeFile noticeFile = purchaseSimpleNoticeService.findFile(batch_no);
            if (noticeFile == null) {
                NoticeFile noticeFile2 = new NoticeFile();
                noticeFile2.setBatch_no(batch_no);
                noticeFile2.setAddress(jcaddress);
                Date create_time = new Date();
                noticeFile2.setCreate_time(create_time);
                noticeFile2.setName(alljc);
                String suffix = alljc.substring(alljc.length() - 4, alljc.length());
                noticeFile2.setSuffix(suffix);
                purchaseSimpleNoticeService.addFlie(noticeFile2);
            } else {
                noticeFile.setAddress(jcaddress);
                noticeFile.setName(alljc);
                String suffix = alljc.substring(alljc.length() - 4, alljc.length());
                noticeFile.setSuffix(suffix);
                purchaseSimpleNoticeService.updatefile(noticeFile);
            }
        }
    }

}

5,存入图片的数据库表SQL,通过BATCH_NO与project表关联

CREATE TABLE `sys_file` (
  `BATCH_NO` varchar(32) NOT NULL COMMENT ‘文件批次号‘,
  `NO` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘编号‘,
  `NAME` varchar(200) DEFAULT NULL COMMENT ‘上传图片名字‘,
  `ADDRESS` varchar(200) NOT NULL COMMENT ‘文件地址‘,
  `SUFFIX` varchar(200) NOT NULL COMMENT ‘文件后缀名称‘,
  `CREATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ‘创建时间‘,
  `MID_ADDRESS` varchar(200) DEFAULT NULL COMMENT ‘中图路径‘,
  `MIN_ADDRESS` varchar(200) DEFAULT NULL COMMENT ‘小图路径‘,
  PRIMARY KEY (`NO`,`BATCH_NO`) USING BTREE,
  KEY `idx_BATCH_NO_NO` (`BATCH_NO`,`NO`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=188 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT=‘图片表‘

6,页面查看图片,需要配置一下

https://www.cnblogs.com/ljmm/p/13026342.html

Java上传图片

标签:har   附件   指定   res   ror   default   content   文件写入   jmm   

原文地址:https://www.cnblogs.com/ljmm/p/13176090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!