SpringMVC文件上传、Json处理

笑着哭i 提交于 2019-12-03 00:54:35

SpringMVC文件上传、Json处理

文件上传

首先导入pom依赖

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
</dependency>

然后在springMVC的配置文件中加入一个Bean:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
</bean>

jsp页面
form要使用多功能表单(enctype=“multipart/form-data”),这样才能实现文件上传

<%--
  Created by IntelliJ IDEA.
  User: 17936
  Date: 2019/10/1
  Time: 15:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    上传的文件:<input type="file" name="img" id="">
    <button type="submit">提交</button>
</form>

</body>

</html>

方法:

    @RequestMapping("/upload")
    public String upload(MultipartFile img){
        try {
            FileUtils.copyInputStreamToFile(img.getInputStream(),new File("D:\\"+img.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "forward:hello3";
    }

Json处理

先编写一个工具类JSONResult :

package com.chen.util;

public class JSONResult {

    // 响应业务状态
    private Integer status;

    // 响应消息
    private String msg;

    // 响应中的数据
    private Object data;

    private String ok;	// 不使用

    public static JSONResult build(Integer status, String msg, Object data) {
        return new JSONResult(status, msg, data);
    }

    public static JSONResult ok(Object data) {
        return new JSONResult(data);
    }

    public static JSONResult ok() {
        return new JSONResult(null);
    }

    public static JSONResult errorMsg(String msg) {
        return new JSONResult(500, msg, null);
    }

    public static JSONResult errorMap(Object data) {
        return new JSONResult(501, "error", data);
    }

    public static JSONResult errorTokenMsg(String msg) {
        return new JSONResult(502, msg, null);
    }

    public static JSONResult errorException(String msg) {
        return new JSONResult(555, msg, null);
    }

    public JSONResult() {

    }

    public JSONResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public JSONResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

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

    public Object getData() {
        return data;
    }

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

    public String getOk() {
        return ok;
    }

    public void setOk(String ok) {
        this.ok = ok;
    }

}


package com.chen.controller;

import com.chen.util.JSONResult;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author嘟嘟
 *
 *
 * 关于结果集处理分五种情况
 * 1.转发到页面(webapp下)
 * 2.转发到action请求
 * 3.重定向到页面
 * 4.重定向到action
 * 5.转发web-inf下页面
 */
@Controller
@RequestMapping("/hello")
public class HelloController {


 @RequestMapping("hello3")
    public String redirectPage2(HttpServletRequest request){
        /*request.setAttribute("msg","重定向到页面的方式");*/
        Object msg = request.getAttribute("msg");
        return "redirect:/hello.jsp";
    }
   
    @RequestMapping("/upload")
    public String upload(MultipartFile img){
        try {
            FileUtils.copyInputStreamToFile(img.getInputStream(),new File("D:\\"+img.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "forward:hello3";
    }


    @ResponseBody
    @RequestMapping("/jsonData3")
    public JSONResult jsonData3(){
        return JSONResult.ok("成功:此参数可以存放字符串、对象、集合都可以,这样可以节省拼接map集合的过程");
    }

    @ResponseBody
    @RequestMapping("/jsonData4")
    public JSONResult jsonData4(){
        return JSONResult.errorMsg("失败,此参数可以存放字符串、对象、集合都可以,这样可以节省拼接map集合的过程");
    }



}

展示结果
在这里插入图片描述
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!