如何使用retrofit2将文件发送到服务器

时间:2021-05-17 06:41:53

标签: java android kotlin

我在使用 Retrofit2 发送音频文件时遇到困难。我得到 import pandas as pd import numpy as np import ma``tplotlib.pyplot as plt import matplotlib.animation as animation df = data.iloc[0:250, 4:12] df1 = df2.iloc[:,0:3] a1 = df.iloc[:,0]/2 a2 = df.iloc[:,1]/2 b1 = df.iloc[:,2]/2 b2 = df.iloc[:,3]/2 c1 = df.iloc[:,4]/2 c2 = df.iloc[:,5]/2 m1 = df1.iloc[:,0] m2 = df1.iloc[:,1] m3 = df1.iloc[:,2] fig ,ax = plt.subplots() l1, = ax.plot (vert1, vert2, 'ro', markersize = m1[0]) l2, = ax.plot (long1, long2, 'ro', markersize = m2[0]) l3, = ax.plot (tras1, tras2, 'ro', markersize = m3[0]) def init(): l1.set_data([],[]) l2.set_data([],[]) l3.set_data([],[]) return (l1,l2,l3) def animate(i,l1,l2,l3): l1.set_data(vert1[i], vert2[i]) l1.set_markersize(m1[i]) l2.set_data(long1[i], long2[i]) l2.set_markersize(m2[i]) l3.set_data(tras1[i], tras2[i]) l3.set_markersize(m3[i]) return (l1,l2,l3) Writer = animation.writers['ffmpeg'] writer = Writer(fps= 100, metadata = dict(artist = 'me'), bitrate = 1800) ani = animation.FuncAnimation(fig, animate, fargs=(l1,l2,l3), init_func=init, interval=10, blit=False) ani.save('/Users/gokulthangavel/Downloads/basic_animation.mp4', writer = writer) plt.show() 。如何在 request.file 中发送文件,而不是在 request.body 中?另外,如何将其作为文件发送(具有原始名称、缓冲区等属性)?这是我的代码:

file: 'okhttp3.MultipartBody$Part@8f3c9ed'

这里我称之为:

@FormUrlEncoded
    @POST("audio/upload")
    fun uploadAudio(
        @Part("file") file: MultipartBody.Part,
        @Field("title") title: String,
        @Field("description") description: String,
        @Field("writer") writer: String,
        @Field("privacy") privacy: Int,
        @Field("duration") duration: Int,
        @Field("secretLink") secretLink: String,
        @Field("isForKids") isForKids: Boolean,
        @Field("language") language: String,
        @Field("tags") tags: List<Tag>,
    ): Call<Any>

当我尝试 private fun uploadAudio() { val sharedPreferences = context?.getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE) if (title == null) { return Toast.makeText(requireContext(), "Title is required", Toast.LENGTH_LONG).show() } if (description == null) { return Toast.makeText(requireContext(), "Description is required", Toast.LENGTH_LONG).show() } if (newAudio == null) { return Toast.makeText(requireContext(), "Audio file is required", Toast.LENGTH_LONG).show() } mainContent.visibility = GONE newAudioProgressBar.visibility = VISIBLE submitButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.upload_avd, 0) val avdSubmitButton = submitButton.compoundDrawables[2] as AnimatedVectorDrawable avdSubmitButton.start() val inputStream = context?.contentResolver?.openInputStream(Uri.parse(newAudio)) val requestFile = RequestBody.create(MediaType.parse("audio/mpeg"), File(newAudio)) val body = MultipartBody.Part.createFormData("file", title, requestFile) RetrofitService().uploadAudio( body, title!!, description!!, sharedPreferences?.getString("token", null).toString(), privacy!!, audioDuration!! / 1000, secretLink.text.toString(), forKids!!, language!!, tagAdapter.tags ).enqueue(object : Callback<Any> { @SuppressLint("LogNotTimber") override fun onFailure(call: Call<Any>, t: Throwable) { d("#Error", "${t.message}") mainContent.visibility = VISIBLE newAudioProgressBar.visibility = GONE Toast.makeText(requireContext(), t.message, Toast.LENGTH_SHORT).show() } @SuppressLint("LogNotTimber") override fun onResponse(call: Call<Any>, response: Response<Any>) { navHostFragment.findNavController().navigate(R.id.myAudiosFragment) Toast.makeText(requireContext(), "Audio uploaded successfully!", Toast.LENGTH_SHORT).show() } }) } 时,它说找不到文件。 newAudio 等于 File(newAudio)

0 个答案:

没有答案
相关问题