我正在使用spring作为后端并为rest客户端进行改造。 我想上传文件
后端代码
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
String name = null;
try {
storageService.store(file);
model.addAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
files.add(file.getOriginalFilename());
name = files.get(files.size()-1).toString();
System.err.println(name.toString());
} catch (Exception e) {
model.addAttribute("message", "FAIL to upload " + file.getOriginalFilename() + "!");
}
return new ResponseEntity<String>(file.getOriginalFilename() , HttpStatus.OK);
}
功能商店
public void store(MultipartFile file) {
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL!");
}
}
android代码选择和上传文件
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = ImagePicker.getImageFromResult(getActivity(), requestCode, resultCode, data);
if (bitmap != null) {
image.setImageBitmap(bitmap);
selection=data.getData();
String[] filepath={MediaStore.Images.Media.DATA};
Cursor cursor=getActivity().getContentResolver().query(selection,filepath,null,null,null);
cursor.moveToFirst();
int column=cursor.getColumnIndex(filepath[0]);
String path=cursor.getString(column);
File file =new File(path);
RequestBody requestfile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image" , file.getName() , requestfile);
upload(body);
}
上传功能
public void upload(MultipartBody.Part path){
Call<ResponseBody> callUploader = iBackEndService.uploadAttachment(path);
callUploader.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG,"UPLODER REUSSI" +" "+response.message());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
Log.e(TAG,throwable.getMessage());
}
});
}
改造映射(我正在使用Retrofit 2.1.0)
@Multipart
@POST("upload")
Call<ResponseBody> uploadAttachment(@Part MultipartBody.Part filePart);
我的上传功能跳转到onResponse,但文件未上传