Когда я загружаю изображение со своей html-страницы, чтобы остальные api работали нормально.
HTML-форма:
<form action="http://localhost:8084/mavenFileUpload/rest/upload/image" method="post" enctype="multipart/form-data">
<input name="file" id="filename" type="file" /><br><br>
<button name="submit" type="submit">Upload</button>
</form>`
API:
@POST
@Path("/image")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) throws UnsupportedEncodingException {
String result = "failed";
// check if all form parameters are provided
if (uploadedInputStream == null || fileDetail == null) {
// return Response.status(400).entity("Invalid form data").build();
return new Gson().toJson(result);
}
// create our destination folder, if it not exists
try {
//Relative to absulate
UPLOAD_FOLDER = getPath();
createFolderIfNotExists(UPLOAD_FOLDER);
} catch (SecurityException se) {
// return Response.status(500)
// .entity("Can not create destination folder on server")
// .build();
return new Gson().toJson(result);
}
String uploadedFileLocation = UPLOAD_FOLDER + "\\" + fileDetail.getFileName();
// String uploadedFileLocation = UPLOAD_FOLDER + "\\" + "xxx.jpg";
try {
saveToFile(uploadedInputStream, uploadedFileLocation);
} catch (IOException e) {
// return Response.status(500).entity("Can not save file" + getPath()).build();
return new Gson().toJson(result);
}
// return Response.status(200)
// .entity("File saved to " + uploadedFileLocation).build();
return new Gson().toJson("success");
}
Проблема в том, что когда я пытаюсь загрузить с Android, данные файла имеют нулевое значение, поэтому файл сохраняется как нулевой с каким-либо символом gurbage
Модифицированный интерфейс Android:
@Multipart
@POST("image/")
Call<String> UploadImage(@Part MultipartBody.Part image, @Part("file") RequestBody file);`
Android-вызов Api:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.build();
Api api = retrofit.create(Api.class);
File file = FileUtils.getFile(getRealPathFromUri(getContext(),fileUri));
RequestBody requestFile = RequestBody.create(
MediaType.parse(getContext().getContentResolver().getType(fileUri)),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
RequestBody name = RequestBody.create(okhttp3.MultipartBody.FORM, file.getName());
Call<String> call = api.UploadImage( body,name);