Java web文件上传接口

前端用的layui的上传组件

导入layui.js
css看情况,不想用layui的样式,就不用导入
html页面

<div data-v-6ec73fb2="" class="el-input">
	<button type="button" class="layui-btn" id="uploadImage">
		<i class="layui-icon">&#xe67c;</i>上传图片
	</button>
</div>
layui.use('upload', function(){
        var upload = layui.upload;

        //执行实例
        var uploadInst = upload.render({
            elem: '#uploadImage' //绑定元素
            ,url: '/api/upload' //上传接口images
            ,accept: 'file'
            ,done: function(res){
                //上传完毕回调
                console.log(JSON.stringify(res));
                layui.use('layer', function(){
                    var layer = layui.layer;

                    layer.msg(res.url, {
                        time: 6000, //6s后自动关闭
                        icon:1
                    });
                });
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });

java后台上传文件接口(js中的url)

第一种方法

@Controller
@RequestMapping("/api")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    @RequestMapping("/upload")
    public @ResponseBody ResponseEntity<Map<String,Object>> uploadImage(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        if (!file.isEmpty()) {
            Map<String, String> resObj = new HashMap<>();
            String path = request.getSession().getServletContext().getRealPath("/");
            System.out.println(path);
            try {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(path, file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>(ResultMap.CODE_ERROR,"后台出错");
            }
            resObj.put("msg", "ok");
            resObj.put("code", "0");
            return new ResponseEntity<>(ResultMap.CODE_SUCCESS,"SUCCESS");
        } else {
            return null;
        }
    }

    @PostMapping("/upload")
    public @ResponseBody ResponseEntity<Map<String,Object>> upload(@RequestParam("file") MultipartFile uploadImage, HttpServletRequest request){
        return new ResponseEntity<>(fileUploadService.uplpad(uploadImage,request));
    }

}

第二种方法

@Controller
@RequestMapping("/api")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

	@PostMapping("/upload")
    public @ResponseBody ResponseEntity<Map<String,Object>> upload(@RequestParam("file") MultipartFile uploadImage, HttpServletRequest request){
        return new ResponseEntity<>(fileUploadService.uplpad(uploadImage,request));
    }

}
public Map<String,Object> uplpad(MultipartFile uploadImage, HttpServletRequest request){
        Map<String,Object> data = ResultMap.getMap(ResultMap.CODE_SUCCESS,"SUCCESS");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String realPath = request.getSession().getServletContext().getRealPath("/upload/");
        System.out.println("文件上传:"+realPath);
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        //是否目录
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String filePath = "";
        String oldName = uploadImage.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            //用于图片上传时,把内存中图片写入磁盘
            uploadImage.transferTo(new File(folder, newName));
            filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/upload/" + format +"/"+ newName;
            System.out.println("filePath = " + filePath);
            data.put("filePath",filePath);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMap.getMap(ResultMap.CODE_ERROR,"上传失败");
    }

ResponseEntity<Map<String,Object>> 返回的数据格式

public class ResponseEntity<T> implements Serializable {

    private static final long serialVersionUID = 2L;

    public static final int CODE_SUCCESS = 0;// 成功

    public static final int CODE_ERROR = 1;// 错误

    public static final int CODE_OK = 200;// 禁止

    public static final int CODE_FORBID = 403;// 禁止

    public static final int CODE_NOT_FOUND = 404;// 不存在

    public static final int CODE_SYSTEM_ERROR = 500;// 系统错误

    public static final int CODE_NO_PERMIT = 401;// 没权限

    public static final int CODE_NO_LOGIN = 4011;// 未登录


    private int code;// 返回代码,0 代表成功,其他都代表不成功 code 只能等于0,1,500,401

    private String msg;// 返回消息提示

    private T data;// 返回的数据,可以存任意可序列化对象

    public ResponseEntity() {
        this.code = CODE_SUCCESS;
        this.msg = "ok";
    }

    public ResponseEntity(int code, String msg) {
        super();
        this.code = code;
        this.msg = msg;
    }

    public ResponseEntity(int code, T data) {
        super();
        this.code = code;
        this.data = data;
    }

    public ResponseEntity(int code, String msg, T data) {
        super();
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ResponseEntity(T data) {
        super();
        this.msg = "success";
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return JacksonUtils.getNEJsonString(this);
    }
}

JacksonUtils .getNEJsonString(this); 写法

	public class JacksonUtils {
		private static final ObjectMapper mapper = new ObjectMapper();
	
	    static {
	        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	    }
	
	    public static final ObjectMapper getObjectMapper() {
	        return mapper;
	    }
		// 转换成json 格式,
	    public static final String getNEJsonString(Object o) {
	        try {
	            return mapper.writeValueAsString(o);
	        } catch (JsonProcessingException e) {
	            throw new RuntimeException(e.getMessage());
	        }
	    }
	}

亲测两种方法都可行

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值