IDEA上传图片到tomcat服务器上


前端页面:

  JS代码:

//选中图片
var form = document.getElementById("danxuan");
// 用表单来初始化
var formData = new FormData(form);
formData.append("multipartFile",formData.get("tplj"));
$.ajax({
    url:"/testList/insertAndPicture" ,
    type:"post",
    data:formData,
    cache: false,
    processData : false, // 不处理发送的数据,因为data值是Formdata对象,不需要对数据做处理  必需写
    contentType : false, // 不设置Content-type请求头  必需写
    async:false,
    success:function (obj){
      $("#tplj").val(""); //将输入框的值置为空字符串
      if(obj.map.statusCode==500){
          alert("添加失败");
          window.location.href="./hsz_questionbase.html";
      }
      if(obj.map.statusCode === 200){
          alert("添加成功");
          window.location.href="./hsz_questionbase.html";
      }
   },
})

  form表单:

<form id="danxuan" action="#" method="post" enctype="multipart/form-data">
    <span>请添加单选题:</span>
    <br />
    <input type="hidden" name="stlx" value="01">
    试题科目:<select id="danxuanstkm" name="stkm">
    <!--后台查询出来填入-->
    </select><br>
    试题名称:<br /><input type="text" name="stmc" required="required" class="form-control " style="width: 300px;"/>
    题干(上传图片或手动输入):
    <input type="file"  id="tpljdanxuan" name="tplj" multiple="multiple" >
    <br />
    <!--<textarea name="sttg" class="form-control" cols="100" rows="6" style="resize: none;width: 600px;"></textarea>-->
    A选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
    B选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
    C选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
    D选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
    <br />
    答案:
    <input type="radio" value="A" name="stda"/>A 
    <input type="radio" value="B" name="stda"/>B 
    <input type="radio" value="C" name="stda"/>C 
    <input type="radio" value="D" name="stda"/>D 
    <br /><br />
    是否显示本题:
    <input type="radio" value="1" name="xsbz" checked="checked"/>显示 
    <input type="radio" value="0" name="xsbz"/>不显示     <br>
    <input class="btn btn-primary" type="submit" onclick="addDX()" value="确认出题"/>
</form>

 

Controller层:

本来这个方法的参数写的是public ResultEntity insert(MultipartFile multipartFile,TestList testList),但是运行的时候一直报参数不匹配,所以就将前台传过来的参数全部列出来,

并在方法中添加到list集合里

//添加试题(包含图片)
    @RequestMapping("/insertAndPicture")
    public ResultEntity insert(MultipartFile multipartFile, String stkm, String stmc, String sttg, String stda, String xsbz, String stlx, HttpServletRequest request){
        TestList testList = new TestList();
        testList.setStkm(stkm);
        testList.setStmc(stmc);
        testList.setSttg(sttg);
        testList.setStda(stda);
        testList.setXsbz(xsbz);
        testList.setStlx(stlx);
        try{
            if (multipartFile.isEmpty()){
                return ResultEntity.error();
            }
            String stdm = getProcedure.getEightCode("nms_code_stdm_id");  //生成8位试题代码流水号//设置存到数据库的试题代码
            testList.setStdm(stdm);
            String sxh = getProcedure.getEightCode("nms_code_stdm_sxh");    //生成8位顺序号流水号
            //设置存到数据库的顺序号
            testList.setSxh(Integer.valueOf(sxh));
            //设置存到数据库的出题人(获取登录用户)
            HttpSession session = request.getSession();
            Login info = (Login) session.getAttribute("info");
            testList.setCtr(info.getUsername());
            testListService.add(multipartFile,testList);
            return ResultEntity.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResultEntity.error();
        }
    }

Service方法:

本来项目没有挂载到tomcat服务器中,所以将图片的位置存到了项目中

 

 

 后来项目要发布到tomcat中,所以重新写了一个方法,将图片存到tomcat下的webapps中

 

 

 

 

package com.tphy.nursing.exam.service;


import com.tphy.nursing.exam.bean.SJXXNEXTGroup;
import com.tphy.nursing.exam.bean.TestList;

import com.tphy.nursing.exam.mapper.TestListMapper;
import com.tphy.nursing.util.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TestListServiceImpl implements TestListService{
        //图片上传路径
        private static final String UPLOAD_DIR = url();
/*使用IDEA内置tomcat使用本方法*/ // public static String url(){ // File file = new File("src/main/webapp/upload"); // String url = file.getAbsoluteFile().toString(); // System.out.println("########图片路径########"+url); // return url; // } /*挂到tomcat服务器上使用本方法*/ public static String url(){ //测试获取tomcat下的webapps路径 String upload; //存到webapps下文件的名称 String tomcat_path = System.getProperty("user.dir"); System.out.println("tomcatPath:" + tomcat_path); //获取Tomcat服务器所在路径的最后一个文件目录 String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("\\")+1,tomcat_path.length()); System.out.println(bin_path); //若最后一个文件目录为bin目录,则服务器为手动启动 if(("bin").equals(bin_path)){//手动启动Tomcat时获取路径为:D:\Software\Tomcat-8.5\bin //获取保存上传图片的文件路径 upload = tomcat_path.substring(0,System.getProperty( "user.dir" ).lastIndexOf("\\")) +"\\webapps"+"\\upload\\"; }else{//服务中自启动Tomcat时获取路径为:D:\Software\Tomcat-8.5 upload = tomcat_path+"\\webapps"+"\\upload\\"; } return upload; } //不建议用new UploadUtils,因为要低耦合,建议把UploadUtils类的upload方法换成静态的方法 private UploadUtils uploadUtils = new UploadUtils(); @Autowired private TestListMapper testListMapper; @Override @Transactional public void add(MultipartFile multipartFile, TestList testList) { String newPath = uploadUtils.upload(UPLOAD_DIR, multipartFile); System.out.println("更新后图片路径:" + newPath); //设置存到数据库的图片路径 testList.setTplj(newPath); //设置存到数据库的创建时间 testList.setCjsj(new Date()); //设置存到数据库的修改时间 testList.setXgsj(new Date()); testListMapper.insert(testList); } }

 

工具类:

  图片:

package com.tphy.nursing.util;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class UploadUtils {
    public String upload(String path,MultipartFile multipartFile){
        //拿到文件的原始名称,即例如a.jpg
        String originalFilename = multipartFile.getOriginalFilename();

        //判断是否为空
        if (originalFilename==null){
            return null;
        }
        //因为上传文件只有一个upload目录,所有的文件都会放在这个文件下,会堆积大量的文件,所以把文件进行分开在upload不同的目录中,利用hash算法就行计算分配目录。例如upload/4/5;或者upload/5/5;这种
        //拿到文件原名称的hashcode
        int hashCode = originalFilename.hashCode();
        //拿到upload下第一个目录的名称upload/n
        int dir1 = hashCode & 0xf;
        //拿到upload下的n目录下的目录名称upload/n/n
        int dir2 = (hashCode & 0xf0) >> 4;
        //拼接路径,path是传过来的文件保存路径,即upload的真实路径,
        String dir = path + File.separator+dir1 + File.separator + dir2;
        //把路径丢到File文件中
        File file = new File(dir);
        //如果d:\1\2这个文件夹不存在,才创建
        if (!file.exists()){
            file.mkdirs();
        }
        //生成新的UUID.randomUUID().toString():为了防止文件名重复
        String newFileName = UUID.randomUUID().toString().replace("-","")+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        InputStream is = null;
        OutputStream os = null;
        try {
            is = multipartFile.getInputStream();
            os = new FileOutputStream(dir+File.separator+newFileName);
            //对文件进行复制
            FileCopyUtils.copy(is,os);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回文件的路径,以便保存到数据库中
        return dir1+File.separator+dir2+File.separator+newFileName;
    }
}

生成不同位数的流水号:

package com.tphy.nursing.util;

import com.tphy.nursing.system.bean.Resources;
import com.tphy.nursing.system.mapper.ResourcesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author :lqw
 * @date :Created in 2020/2/28 10:35
 * @description:调用存储过程
 * @modified By:
 * @version: 1
 */
@Component
public class GetProcedure {

    @Autowired
    ResourcesMapper resourcesMapper ;

    /**
     * create by: lqw
     * description: 获取10位自增id
     * create time: 2020/3/4 17:50
     *
      * @param  :
     * @return  * @return : null
     */
    public  String getCode(String type){

        Map<String,String> params = new HashMap<>();
        params.put("prm_lx",type);
         resourcesMapper.GetProcedure(params);
         return params.get("prm_bh");
    }

    /**
     * create by: lqw
     * description: 获取两位自增id
     * create time: 2020/3/4 17:51
     *
      * @param  :
     * @return  * @return : null
     */
    public String getTwoCode(String type){
        Map<String,String> params = new HashMap<>();
        params.put("prm_lx",type);
        resourcesMapper.GetProcedure(params);
        return params.get("prm_bh").substring(8);

    }
    /**
     * create by: lqw
     * description: 获取三位自增id
     * create time: 2020/3/4 17:51
     *
      * @param  :
     * @return  * @return : null
     */
    public String getThreeCode(String type){
        Map<String,String> params = new HashMap<>();
        params.put("prm_lx",type);
        resourcesMapper.GetProcedure(params);
        return params.get("prm_bh").substring(7);

    }
    /**
     * create by: lqw
     * description: 获取4位自增id
     * create time: 2020/3/4 17:51
     *
      * @param  :
     * @return  * @return : null
     */
    public String getFourCode(String type){
        Map<String,String> params = new HashMap<>();
        params.put("prm_lx",type);
        resourcesMapper.GetProcedure(params);
        return params.get("prm_bh").substring(6);

    }
    /**
     * create by: lqw
     * description: 获取6位自增id
     * create time: 2020/3/4 17:51
     *
      * @param  :
     * @return  * @return : null
     */
    public String getSixCode(String type){
        Map<String,String> params = new HashMap<>();
        params.put("prm_lx",type);
        resourcesMapper.GetProcedure(params);
        return params.get("prm_bh").substring(4);

    }
    /**
     * create by: lqw
     * description: 获取8位自增id
     * create time: 2020/3/4 17:51
     *
      * @param  :
     * @return  * @return : null
     */
    public String getEightCode(String type){
        Map<String,String> params = new HashMap<>();
        params.put("prm_lx",type);
        resourcesMapper.GetProcedure(params);
        return params.get("prm_bh").substring(2);

    }

}

返回结果集:

package com.tphy.nursing.util;

import java.util.HashMap;
import java.util.Map;

public class ResultEntity {
   public Map<String,Object> map=new HashMap<String, Object>();
    public ResultEntity put(String str, Object obj){
        this.map.put(str,obj);
        return this;
    }
    public static ResultEntity success(){
        ResultEntity entity=new ResultEntity();
        entity.map.put("statusCode",200);
        entity.map.put("message","响应成功");
        return entity;
    }
    public static ResultEntity error(){
        ResultEntity entity=new ResultEntity();
        entity.map.put("statusCode",500);
        entity.map.put("message","响应失败");
        return entity;
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM