sprootBoot上传和下载文件

1.单文件上传:传到服务器的 F:\uploadSrc目录下

  @RequestMapping("/upload")
    public @ResponseBody
    String upload(@RequestParam("file") MultipartFile file){
        try {
            if(file.isEmpty()){
                return "file is empty";
            }
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String filePath = "F:\\uploadSrc\\";
            String path = filePath+fileName;
            File dest = new File(path);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return "upload success";

        }catch (IllegalStateException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return "upload failed";
    }

2.多文件上传:目录同上

@PostMapping("/batch")
    public @ResponseBody
     String handleFileUpload(HttpServletRequest request){
        List<MultipartFile> fileList = ((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for(int i=0;i<fileList.size();++i){
            file = fileList.get(i);
            String filePath = "F:\\uploadSrc\\";
            if(!file.isEmpty()){
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                }catch (Exception e){
                    stream = null;
                    e.printStackTrace();
                    return "the"+i+"file upload failure";
                }
            }else {
                return "the"+i+"file is empty";
            }
        }
        return "upload multiFile success";
    }

3.下载文件:

@GetMapping("/download")
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response){
        String fileName = "img11.png";  //下载时的文件名
        if(fileName!=null){
            File file = new File("F:\\downSrc\\img11.png");
            if(file.exists()){
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition","attachment;fileName="+fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i!=-1){
                        os.write(buffer,0,i);
                        i = bis.read(buffer);
                    }
                    bis.close();
                    fis.close();
                    return "download success";
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return "failure";
    }

4:调试,可以用谷歌的postman或安卓调试也可以,这里使用安卓的xutils框架调试,由于我的电脑本地服务器连我的热点,可以使用ipconfig查看ip,然后使用即可。
下载:

    fun checkNewVersionApk(){
        var url = "http://ip:8080/download"
        var params = RequestParams(url)
       var ss = Environment.getExternalStorageDirectory().path+"/apk/111.png"
        params.saveFilePath = ss
        x.http().get(params,object :Callback.ProgressCallback<File>{
            override fun onFinished() {
                    Log.d("download","finished:"+ss)
            }

            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                   //下载中的进度
                Log.d("download","onLoading")
            }

            override fun onStarted() {

            }

            override fun onSuccess(result: File?) {
                //下载完成
//                var intent = Intent(Intent.ACTION_VIEW)
//                intent.setDataAndType(Uri.fromFile(result),"application/vnd.android.package-archive")
//                startActivity(intent)
                Log.d("download","onSuccess")
            }

            override fun onWaiting() {

            }

            override fun onCancelled(cex: Callback.CancelledException?) {
            }

            override fun onError(ex: Throwable?, isOnCallback: Boolean) {
                Log.d("download","onError"+ex.toString())
            }

        })
    }

上传:

fun upLoadFile(filePath:String){
        var path = filePath
        var params = RequestParams("http://ip:8080/upload")
        params.isMultipart = true
        params.addBodyParameter("file",File(path))
        x.http().post(params,object :Callback.CommonCallback<String>{
            override fun onFinished() {

            }

            override fun onSuccess(result: String?) {
                Log.d("upload","onSuccess")
            }

            override fun onCancelled(cex: Callback.CancelledException?) {
            }

            override fun onError(ex: Throwable?, isOnCallback: Boolean) {
                Log.d("upload","onError"+ex.toString())
            }

        })
    }

如果使用知乎的图片选择框架,返回uri后,得转为真正的地址:

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==111&&resultCode== Activity.RESULT_OK){
            val result = Matisse.obtainResult(data)
            Glide.with(this).load(result.get(0)).into(glideImage);
            if(result!=null&&result.size>0) {
                for (item in result) {
                    Log.d("matisse", item.toString());
                    var uploadUrl = getRealPathFromUri(this@MainActivity,item)
                    Log.d("matisse",uploadUrl)
                    upLoadFile(uploadUrl);
                }
            }else{
                Log.d("matisse", "error");
            }
        }
    }

转换地址:

    public  fun getRealPathFromUri(context:Context, contentUri:Uri):String {
        var cursor: Cursor? = null
        try {
            var proj =  arrayOf(MediaStore.Images.Media.DATA )
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            var column_index:Int = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

到此,服务器的下载上传和客户端的上传下载都完毕了,后面搞搞neety,在项目里加点聊天功能,实现客户端的聊天,不知道难不难,哈哈。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值