springboot 项目实现图片上传

搞了一天多,遇到了很多问题,整理下来记录一下,好用的请点赞哦

前端代码html:

<button style="position:relative;" class="btn btn-primary" id="btn" name="btn">上传图片</button>
<input type="file" name="file" id="file"  onchange="uploadImage(this);" style="opacity:0;width:100%;height:100%;position:absolute;top:0;left:0">

js提交:

function uploadImage(obj) {
    console.log("obj="+obj)
    var f = $(obj).val();
    console.log("f="+f);

    if(f == null ||f == undefined || f == ""){
        return false;
    }
    if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f)){
        alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
        $(obj).val("");
        return false;
    }

------------------------------------
单图上传

    var formData = new FormData();
     // debugger
    console.log($(obj)[0].files[0])
    formData.append("file",$("#file")[0].files[0]);

---------------------------------------

批量上传

var formData = new FormData();
 // debugger
console.log($(obj)[0].files[0])
var files = $("#file")[0].files;
for(var i=0;i<files.length;i++){
    formData.append("file",$("#file")[0].files[i]);
}
----------------------------------


    $.ajax({
        type:"POST",
        url : apiPath+"/admin/upload/uploadimg",
        data : formData,
        cache : false,
        processData : false,    //JQuery不处理发送数据
        // contentType : 'multipart/form-data',//(如果这样,会导致contentType没有边界boundary,导致文件解析失败,后台报错Could not parse multipart servlet request;)
        contentType : false,
        success : function(result) {
            if(result.code == "200") {
                console.log(result.data);
                alert("图片上传成功")
                window.location.reload()
            }
        }
    });
}

后台服务Controller:

package com.kankan.service.admin.upload;

import com.kankan.core.entity.R;
import com.kankan.module.sys.entity.SysQrCode;
import com.kankan.module.sys.logic.SysQrCodeLogic;
import com.kankan.module.system.entity.GlobalConfig;
import com.kankan.module.system.logic.GlobalConfigLogic;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/admin/upload/")
@Api
public class UploadImageController {

    /*@Value("${admin.images.uploadPath}")
    private String uploadPath;*/
    @Resource
    SysQrCodeLogic sysQrCodeLogic;

    @Resource
    GlobalConfigLogic globalConfigLogic;


    @ApiOperation(value = "上传文件")
    @PostMapping("uploadimg")
    public R<Map> uploadImages1(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        GlobalConfig config = globalConfigLogic.getByGlobalKey("admin.images.uploadPath");
        String uploadPath = config.getGlobalValue();

        Map resultMap = new HashMap();
//        uploadPath = "c:/java/project/images/";
        String fileName = uploadFile(uploadPath,file);

        SysQrCode code = new SysQrCode();
        code.setPath(fileName);
        code.setStatus("1");
        code.setCtime(new Date());
        code.setCtime(new Date());
        sysQrCodeLogic.save(code);
        resultMap.put("path",fileName);
        return R.ok(resultMap);
    }


    private String uploadFile(String uploadPath,MultipartFile file){
        InputStream inputStream = null;
        OutputStream os = null;
        String path = null;
        String fileName = new Date().getTime()+"_"+file.getOriginalFilename();
        try{
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(uploadPath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            inputStream = file.getInputStream();
            path = tempFile.getPath() + File.separator + fileName;
            os = new FileOutputStream(path);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            // 完毕,关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  fileName;
    }

    @ApiOperation(value = "批量上传文件")
    @PostMapping("uploadimgs")
    public R<Map> uploadImages1(@RequestParam("file") MultipartFile[] files){
        GlobalConfig config = globalConfigLogic.getByGlobalKey("admin.images.uploadPath");
        String uploadPath = config.getGlobalValue();
//        uploadPath = "c:/java/project/images/";
        Map resultMap = new HashMap();
        uploadPath = "c:/java/project/images/";
        for(MultipartFile file:files){
            String fileName = uploadFile(uploadPath,file);
            SysQrCode code = new SysQrCode();
            code.setPath(fileName);
            code.setStatus("1");
            code.setCtime(new Date());
            code.setCtime(new Date());
            sysQrCodeLogic.save(code);
        }

        resultMap.put("path","");
        return R.ok(resultMap);

    }
}

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值