客户端Android/web上传文件+服务端SpringBoot 接收文件

上传文件真是各种踩坑了。。。然后现在大概整理一下吧就,我主要是以图片为主,其他类型的比较少用到,但是也是可以上传的。

服务端SpringBoot 接收工具类


/*
 *@Author:Swallow
 *@Date:2019/2/27
 *
 */
public class PhotoUtil {
    private static Logger logger = LoggerFactory.getLogger(PhotoUtil.class);
//该路径是配置绝对路径进行上传
    public final static String SYS_PATH = "E:\\work-space\\idea\\lqx\\src\\main\\resources\\static\\img\\pic";
    public final static String STATIC_PATH = "/img/pic/";
//这个是获取服务器上边的实际路径,保存的图片会出现在target当中
    public final static String REAL_PATH = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+"/img/pic";
    public static String savePhoto(MultipartFile multipartFile, String id){
        String inputname = multipartFile.getOriginalFilename();
        logger.info("成功接收图片:"+inputname);
        String outname = id +".jpg";
        File savedFile =  new File(REAL_PATH , outname);
        logger.info("成功保存图片:"+outname);
        try {
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),savedFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outname;
    }
}

调用:

//举个栗子
@PostMapping("/notice")
//设置接收文件参数
    public String add(@RequestParam("image") MultipartFile files,
                      Notice notice, HttpSession session){
        Integer id = (Integer) session.getAttribute("userId");
        if (files!=null){
            MultipartFile multipartFile = files;
            Long startTs = System.currentTimeMillis(); // 当前时间戳
            String outname = PhotoUtil.savePhoto(multipartFile,startTs+"");
            notice.setPic(PhotoUtil.STATIC_PATH + outname);
        }
        notice.setAdminId(id);
        notice.setSendDatetime(GetDateUtil.getDateTime2());
        noticeMapper.save(notice);
        return  "redirect:/notices";
    }

服务端接收吧,可以说有两种方式,一种是获取相对路径(我感觉这个比较保险),但是图片是传到target当中,不会传到项目目录下边。所以,如果需要传到项目目录下边,可以自己配置文件的绝对路径,然后还有就是,要配置静态资源文件路径。

我是在application.yml文件里边配置的(空格可能自己再调整下)

spring:
  mvc:
    static-path-pattern: /**
  resources:
    static-locations: classpath:/public/,classpath:/static/

如果需要配置接收文件的大小

spring:
  servlet:
    multipart:
      max-file-size: 500MB
      max-request-size: 500MB

 

然后web端的上传比较简单,我用了个bootstrap的插件

文件上传的插件百度应该蛮多的


图片加载失败...
选择图片 修改

然后表单的地方,注意要设置一下

Android文件选择获取路径  参考

https://www.cnblogs.com/panhouye/p/6751710.html

 

获取到文件的路径以后,我通过okHttp发送请求,进行文件上传

调用参考

private void upFile() {
        new Thread(){
            public void run(){
                Message message = handler.obtainMessage();
                //传入参数
                Map map = new HashMap<>();
                map.put("id", String.valueOf(disId));
//                    Log.e("TAG takeSuccess", "id:" + disId);
                String result = null;
                try {
//传入参数,url,参数,文件路径
                    result = OkHttpUtil.uploads(MyConstant.RESCUER_UP_IMAGE, map, path);
                    Log.e("上传打印--result1", result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    Boolean success = jsonObject.getBoolean("success");
//                    Boolean success = JsonUtils.JsonSuccess(result);
                    if(success) {
                        //请求成功发送用户数据
                        message.what = MyConstant.COM_SUCCESS;
                        message.obj = result;
                        handler.sendMessage(message);
                    }else {
                        //请求失败发送失败信息
                        String msg = JSONObject.parseObject(result).getString("message");
                        message.what = MyConstant.NET_ERROR;
                        message.obj = msg;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

工具类(文件与参数一起请求到服务端)

/**
 * @author: swallow
 * @date: 2019/12/9
 **/
public class OkHttpUtil {
    private static final int IMG_SUCCESS = 2;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static final MediaType FROM_DATA = MediaType.parse("multipart/form-data");
    private static final MediaType AUDIO = MediaType.parse("audio/mp3");
    private static final MediaType VIDEO = MediaType.parse("video/mp4");

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20*1000, TimeUnit.MILLISECONDS)
            .readTimeout(20*1000,TimeUnit.MILLISECONDS)
            .writeTimeout(20*1000, TimeUnit.MILLISECONDS).build();

   

    //上传图片与参数
    public static String uploads( String url,Map params,String filepath) throws IOException {
        OkHttpClient client = new OkHttpClient();

        File file = new File(filepath);

        MultipartBody.Builder mbuilder = new MultipartBody.Builder();
        if(params != null && params.size() > 0) {
            for (String param : params.keySet()) {
                mbuilder.addFormDataPart(param,params.get(param));
            }
        }
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG,file);
        RequestBody requestBody = mbuilder
                .setType(MultipartBody.ALTERNATIVE)
                .addFormDataPart("file", file.getName(), fileBody)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        //Response response = client.newCall(request).execute();
        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();
            return result;
        }
    }

   
}

 

你可能感兴趣的:(JavaWeb)