【问题标题】:Saving image to server directory using SpringBoot with Android使用带有 Android 的 Spring Boot 将图像保存到服务器目录
【发布时间】:2019-12-20 00:13:56
【问题描述】:

我正在开发一个将图像发送到服务器的应用程序。我想将来自应用程序的照片保存在本地服务器端文件夹中。为此,我使用 SpriingBoot 进行 API 开发,在 Android 上,我使用 Volley 库通过 Json 提交请求。

我已经尝试将请求中传入的字符串转换为字节[],然后将其保存为 Image.io 格式文件,但无法保存图像。谁能帮我把图片保存到本地服务器目录?

代码安卓:

public class MainActivity extends AppCompatActivity {

public static final String REGISTER_URL = "http://192.168.1.8:8080/api/paciente";
public static final String KEY_IMAGE = "foto";
String foto = "null";
public static final String TAG = "LOG";
private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button enviar = (Button) findViewById(R.id.enviar);


    enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            registerForms();

        }
    });
}

public void tirarFoto(View view) {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        Bundle bundle = data.getExtras();
        if (bundle != null) {
            Bitmap img = (Bitmap) bundle.get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            img.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            foto = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
            Toast toast = Toast.makeText(getApplicationContext(), "Foto anexada", Toast.LENGTH_LONG);
            toast.show();
        }
    }
}


@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

public void registerForms() {

    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            if (response.contains("Erro")) {
                //progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "Erro ao enviar", Toast.LENGTH_LONG).show();
                Log.i(TAG, "Lat: " + "Caiu aqui");
            } else {
                //progressDialog.dismiss();
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                Toast.makeText(MainActivity.this, "Enviado com sucesso!", Toast.LENGTH_LONG).show();
                startActivity(intent);
            }

        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                  //progressDialog.dismiss();
                    Toast.makeText(MainActivity.this, "Enviado com sucesso!", Toast.LENGTH_LONG).show();
                    Log.i(TAG, "String: " + foto);
                }
            }) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError{
            Map<String, String> map = new HashMap<String, String>();
            map.put(KEY_IMAGE, foto);
            Log.i(TAG, "Lat: " + map);
            return map;

        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
}

代码 API:

服务:

@RequestMapping(value = "/paciente", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = {
        MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, "application/json" })
public @ResponseBody Paciente cadastraPaciente(@Valid Paciente paciente) throws Exception {
    byte[] imgBytes = Base64.decodeBase64(foto.getBytes());
    try{
        FileOutputStream fos = new FileOutputStream("C:/Users/carlo/Downloads/SisCAF/images/myImage1.png");
         fos.write(imgBytes);
         FileDescriptor fd = fos.getFD();
         fos.flush();
         fd.sync();
         fos.close(); 
     }


    return paciente;
}

和代码一样,返回image属性为null

【问题讨论】:

  • 假设BufferedImage 被正确读取,请尝试使用relative 提及您的path,如下所示:"./out.jpg",它有效吗?
  • @Phill 问题是将 ByteArrayInputStream 转换为 ByteArrayInputStream 因为它返回一个空图像
  • 你的意思是 bis 是空的,对吧?
  • 菲尔,是的,是空的
  • 好的,byte[ ] encoded 呢?

标签: java android rest spring-boot web


【解决方案1】:

通过使用@noname 的后端实现,您可以使用Retrofit 以一种简洁明了的方式轻松地将图像发送到您的服务器:

添加到构建文件:

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

像这样在您的应用中配置改造:

public class NetworkClient {
private static final String BASE_URL = "http://localhost:8080";
private static Retrofit retrofit;
public static Retrofit getRetrofitClient(Context context) {
    if (retrofit == null) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}

定义你的 API 调用和简单的接口:

public interface UploadAPIs {
@Multipart
@POST("/upload")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part file, @Part("name") RequestBody requestBody);

}

最后,使用上述配置发送您的图像,如下所示:

private void uploadToServer(String filePath) {
 Retrofit retrofit = NetworkClient.getRetrofitClient(this);
 UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
 //Create a file object using file path
 File file = new File(filePath);
 // Create a request body with file and image media type
 RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
 // Create MultipartBody.Part using file request-body,file name and part name 
 MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);
 //Create request body with text description and text media type
 RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
 // 
 Call call = uploadAPIs.uploadImage(part, description);
 call.enqueue(new Callback() {
     @Override
     public void onResponse(Call call, Response response) {
     }
     @Override
     public void onFailure(Call call, Throwable t) {
     }
 });

}

【讨论】:

    【解决方案2】:

    这是我在我的 PictureManager 类的 spring 应用程序中使用的方法:

    public static void storeFile(MultipartFile[] files) {
        for (MultipartFile file : files) {
          String[] fileNamePieces = file.getOriginalFilename().split("_");
    
          File picture = new File("\\\\IP-SERVER\\folder\\stored\\Photos\\" + fileNamePieces[0] + "\\");
          String productId = getProductId(fileNamePieces[0], LABEL_TYPE.valueOf(fileNamePieces[1]).getLableType());
    
          if (!picture.exists())
            picture.mkdirs();
          try {
            copyFileToLocation(file, "\\\\IP-SERVER\\folder\\Quality stored\\Photos\\Arch\\" + productId.trim() + ".jpg");
            copyFileToLocation(file, picture + "\\" + file.getOriginalFilename());
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    

    我在主 RestController 中映射,例如:

    @PostMapping("/file")
      public void handleFileUpload(@RequestParam("files") MultipartFile[] files) throws IOException {
        PictureManager.storeFile(files);
      }
    
    

    在这里你有我在 android 中实现的方法,我也在设置 URL 到我的 spring 方法映射的 http,例如:http://spring-app:8080/storeFile 该方法需要设置为 POST 方法。

    public void sendFile(final File [] files){
        Thread t = new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
              httpURLConnection.setUseCaches(false);
              httpURLConnection.setRequestMethod("POST");
              httpURLConnection.setChunkedStreamingMode(4096);
              httpURLConnection.setDoOutput(true);
              httpURLConnection.setDoInput(true);
              httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
              httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
              httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=****");
              BufferedOutputStream dos = new BufferedOutputStream(httpURLConnection.getOutputStream());
    
              dos.write("Content-Type: multipart/form-data; boundary=****\r\n".getBytes());
              dos.write("Content-Transfer-Encoding: binary\r\n".getBytes());
              for (File file : files) {
    //            if(file.length() <= 0)
    //              continue;
    
                BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file.getAbsoluteFile()));
    
                String what_is_here = String.format("Content-Disposition: form-data; name=\"files\"; filename=\"%s\"\r\n", file.getName());
                dos.write("--****\r\n".getBytes());
                dos.write(what_is_here.getBytes());
                dos.write("\r\n".getBytes());
                dos.flush();
                byte[] b = new byte[(int) file.length()];
    
                for (int i = 0; i < b.length; i++) {
                  b[i] = (byte) fileInput.read();
                }
    
                Log.wtf("BYUTE", b.length + "");
                dos.write(b);
                dos.write("\r\n".getBytes());
                dos.flush();
                fileInput.close();
              }
              dos.write("--*****--\r\n".getBytes());
              dos.flush();
              dos.close();
              Log.wtf("STATUS", httpURLConnection.getResponseCode() + "");
            } catch(UnsupportedEncodingException e){
              e.printStackTrace();
            } catch(IOException e){
              e.printStackTrace();
            } finally {
              httpURLConnection.disconnect();
            }
          }
        });
        t.start();
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多