java上传文件前端响应

第一种

在包下创建上传前端响应类

import com.alibaba.druid.filter.AutoLoad;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 上传响应参数
 * @param <E>
 */
//以下是lombok插件注解
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Resp<E> {
    //返回状态码 如 200 403
    private  String code;
    //返回信息
    private  String Msg;
    //也可定义为  Object body  都表示任意类型的意思
    private  E body;//模板类型

    /**
     * 成功时候方法
     * @param body
     * @param <E>
     * @return
     */
   public static<E> Resp<E> success(E body){
       return  new Resp<E>("200","上传成功!",body);
   }

    /**
     * 上传失败时的方法
     * @param code
     * @param msg
     * @param <E>
     * @return
     */
    public static<E> Resp<E> fail(String code,String msg){
        return  new Resp<E>(code,msg,null);
    }
}


在controller层接收前端上传的文件

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller

public class uploadController {
    @Autowired
    private UploadService uploadService;
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    @ResponseBody
	//返回类型根据自定义的返回类型 不一定和我一样 
    public Resp<String> upload(@RequestParam("file")MultipartFile file){

        return  uploadService.upload(file);
    }

}

在servcie包下建立upload接口及其实现类处理业务

import org.springframework.web.multipart.MultipartFile;
/**
*上传业务类
*/
public interface UploadService {
	//上传接口
    Resp<String > upload(MultipartFile file);
}

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 上传业务实现类
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Override
    public Resp<String> upload(MultipartFile file) {
        //判断上传的文件是不是空
        if (file.isEmpty()){
            return Resp.fail("400","文件为空!");
        }
        //文件不为空的情况
        //获得原始文件名(前端传过来的文件名) 带有拓展名
        //原始文件名存在一定问题
        String OriginalFilename=file.getOriginalFilename();
        //根据 时间戳+拓展名=服务器文件名
        // 确定服务器文件名(经过字符操作加上拓展名)
        String fileName= System.currentTimeMillis()+"."+OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1);
        //控制台查看服务器文件名
        System.out.println(fileName);
        //确定文件储存位置
        //  文件保存路径 注意最后加上双反斜杠 转义字符所有双反斜杠
        String filePath="F:\\Test\\";
        //目标文件路径 (实际创建在硬盘的文件)
        File dest=new File(filePath+fileName);
        //判断dest的父目录是否存在
        if(dest.getParentFile().exists())
            dest.getParentFile().mkdirs();

        try {
                //前端传过来的文件拷贝在本地
                file.transferTo(dest);
            }catch (Exception e){
                e.printStackTrace();
               return Resp.fail("500",OriginalFilename+"上传失败!");

            }
            //上传成功 返回前端穿过来的文件名
            return Resp.success(fileName);


    }
}

第二种

首先我们的前端是普通的文件上传

  <form action="上传的地址" enctype="multipart/form-data" method="post">

        文件上传:<input type="file" name="file" value="请选择文件上传">

        <br>

        <input type="submit" value="提交"><input type="reset" value="重置">

       </form>

编写一个文件上传工具方法类,里面方法都可调用,根据自己实践的来

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 输出JSON数据
     *
     * @param response
     * @param jsonStr
     */
    public void writeJson(HttpServletResponse response, String jsonStr) {
        response.setContentType("text/json;charset=utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(jsonStr);
            pw.flush();
        } catch (Exception e) {
            logger.info("输出JSON数据异常", e);
        }finally{
            if(pw!=null){
                pw.close();
            }
        }
    }
    /**
     *
     * 向页面响应json字符数组串流.
     *
     * @param response
     * @param jsonStr
     * @throws IOException
     * @return void
     */
    public void writeJsonStr(HttpServletResponse response, String jsonStr) throws IOException {

        OutputStream outStream = null;
        try {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            outStream = response.getOutputStream();
            outStream.write(jsonStr.getBytes("UTF-8"));
            outStream.flush();
        } catch (IOException e) {
            logger.info("输出JSON数据异常(writeJsonStr)", e);
        } finally {
            if(outStream!=null){
                outStream.close();
            }
        }
    }

    public void writeJsonStr(HttpServletResponse response, InputStream in) throws IOException {

        if(null == in ){
            return ;
        }
        OutputStream outStream = null;
        try {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            outStream = response.getOutputStream();
            int len = 0;
            byte[] byt = new byte[1024];
            while ((len = in.read(byt)) != -1) {
                outStream.write(byt, 0, len);
            }
            outStream.flush();

        } catch (IOException e) {

            logger.info("输出JSON数据异常(writeJsonStr)", e);
        } finally {
            if(outStream!=null){
                outStream.close();
                in.close();
            }
        }
    }


    /**
     * 输出JSON数据
     *
     * @param response
     * @param
     */
    public void writeJson(HttpServletResponse response, Object obj) {
        response.setContentType("text/json;charset=utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(JSON.toJSONString(obj));

            pw.flush();
        } catch (Exception e) {
            logger.info("输出JSON数据异常", e);
        }finally{
            if(pw!=null){
                pw.close();
            }
        }
    }




    public void writeHtml(HttpServletResponse response, String html) {
        response.setContentType("text/html;;charset=utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(html);
            pw.flush();
        } catch (Exception e) {
            logger.info("输出HTML数据异常", e);
        }finally{
            if(pw!=null){
                pw.close();
            }
        }
    }
}

然后编写测试类继承上面的工具类

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;



/**
     * 照片上传工具类
     * @author admin
     *
     */
    @Controller
    public class test extends BaseController {
    @ResponseBody
    @RequestMapping("/doupload")
    public void uploadPicture(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
    //这个实例化是Result风格理解的就是一种返回格式{code:XX,msg:XX,data:XX}
        ResponseResult result = new ResponseResult();  
        Map<String, Object> map = new HashMap<String, Object>();
        File targetFile = null;
        String url = "";//返回存储路径
        int code = 1;
        System.out.println(file);
        String fileName = file.getOriginalFilename();//获取文件名加后缀
        if (fileName != null && fileName != "") {
            //String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
            //文件存储的路径
            String returnUrl = "C:\\bskj\\Web\\yrq\\nginx-1.16.1\\html";//存储路径
            //文件存储的路径
            String path = "C:\\bskj\\Web\\yrq\\nginx-1.16.1\\html"; //文件存储位置
            System.err.println(path);
            //时间转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            //取出文件后缀名
            String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            //组成新的图片名称
            fileName = sdf.format(new Date()) + "_" + new Random().nextInt(1000) + fileF;//新的文件名
            //路径在哪个目录下
            String fileAdd = "photo";
            //获取文件夹路径
            File file1 = new File(path + "/" + fileAdd);
            //先判断文件是否存在
            //如果文件夹不存在则创建
            if (!file1.exists() && !file1.isDirectory()) {
                file1.mkdir();
            }
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            try {
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);
                //文件路径如(C:\Users\yuRongQi\上传图片测试/photo/20200410_741.jpg)
                //url=returnUrl+"/"+fileAdd+"/"+fileName;
                code = 0;
                result.setCode(code);
                result.setMessage("图片上传成功");
                //map.put("url", fileAdd+"/"+fileName);
                map.put("url", fileName);
                result.setResult(map);
            } catch (Exception e) {
                e.printStackTrace();
                result.setMessage("系统异常,图片上传失败");
            }
        }
        writeJson(response, result);
    }
   }

在启动类里配置注入一下

@SpringBootApplication
@Configuration
public class PhonegdApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(PhonegdApplication.class, args);
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大
        factory.setMaxFileSize(DataSize.ofMegabytes(10));
        //该方法已降级
        //factory.setMaxRequestSize("30MB");
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(100));
        return factory.createMultipartConfig();
    }
}

走到这里,我们上传的前后端就已经写好了(但是文件有大小限制)

我们就去调整,给大一点空间,根据自己调整,在配置文件appliaction中增加

spring:
  servlet:
    multipart:
      max-file-size: 10MB    ##单个文件最大大小
      max-request-size: 100MB  ##上传数据总大小
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值