簡體   English   中英

如何將 Stream 中的圖像另存為在改造 2 中發送到 wcf web 服務的圖像

[英]How to save as Image From Stream which is send in retrofit2 to wcf web service

I am sending a image file to wcf web service using retrofit, on saving side of wcf web service i am unable to save the stream file.

在 android 我創建喜歡

//ApiInterface.class
@Multipart
@POST("RestService/json/PostUploadFile/")
Call<UploadFileResponse> uploadFile(@Part MultipartBody.Part file); 

服務電話就像

File file = new File(assets.get(0).getPath());
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part part = MultipartBody.Part.createFormData("imageData", file.getName(), requestFile);

//api call method
callUploadFile(part, this);

private void callUploadFile(MultipartBody.Part part,
                               MainInteractor.OnFinishedListener listenerP) {
            final MainInteractor.OnFinishedListener listener = listenerP;

            HashMap<String, String> headerMap = new HashMap<>();
            headerMap.put("SessionID", "");
            headerMap.put("UserName", "");
            OkHttpClient httpClient = ConnectToService.newInstance().addHeaders(getContext(), headerMap);

            ApiInterface apiService =
                    ConnectToService.newInstance()
                            .getClient(httpClient).create(ApiInterface.class);

            Call<UploadFileResponse> call = apiService.uploadFile(part);
            call.enqueue(new Callback<UploadFileResponse>() {
                @Override
                public void onResponse(Call<UploadFileResponse> call, Response<UploadFileResponse> response) {
                    onFinished(response.body().getResult());
                }

                @Override
                public void onFailure(Call<UploadFileResponse> call, Throwable t) {
                    if (t.getLocalizedMessage() != null) {
                        onFinishedFailure(t.getLocalizedMessage());
                    }
                }
            });
        }

在 wcf 網絡服務中,我在消息中獲取數據,但是當我保存時,我得到參數異常錯誤。 獲取消息中的數據 保存時出錯

編輯:下面的代碼有效

Bitmap bm = BitmapFactory.decodeFile(assets.get(finalX).getPath());
                        Bitmap bitmap = Bitmap.createScaledBitmap(bm, 480, 480, true);
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos); //bm is the bitmap object
                        byte[] byteArray = baos.toByteArray();
                        RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), byteArray);
                        callUploadFile(body, "File_" + finalX, MainFragment.this);

調用服務方法

private void callUploadFile(RequestBody body, String fileName,
                           MainInteractor.OnFinishedListener listenerP) {
        final MainInteractor.OnFinishedListener listener = listenerP;

        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("SessionID", "");
        headerMap.put("UserName", "");
        headerMap.put("FileName", fileName);
        OkHttpClient httpClient = ConnectToService.newInstance().addHeaders(getContext(), headerMap);

        ApiInterface apiService =
                ConnectToService.newInstance()
                        .getClient(httpClient).create(ApiInterface.class);

        Call<UploadFileResponse> call = apiService.uploadFile(body);
        call.enqueue(new Callback<UploadFileResponse>() {
            @Override
            public void onResponse(Call<UploadFileResponse> call, Response<UploadFileResponse> response) {
                if (response != null && response.body() != null) {
                    onFinished(response.body().getResult());
                } else {
                    if (response.message() != null) {
                        onFinishedFailure(response.message());
                    }
                }
            }

            @Override
            public void onFailure(Call<UploadFileResponse> call, Throwable t) {
                if (t.getLocalizedMessage() != null) {
                    onFinishedFailure(t.getLocalizedMessage());
                }
            }
        });
    }

在 wcf 服務中

public string uploadFile(Stream imageData)
        {
            string fileName = WebOperationContext.Current.IncomingRequest.Headers.Get("fileName");
            string fileFullPath = "D:\\Share\\srinidhi\\Temp_" + fileName + ".Jpeg";

            Image img = System.Drawing.Image.FromStream(imageData);
            img.Save(fileFullPath, ImageFormat.Jpeg);

            return "success";
        }

在 api 調用

@POST("RestService/json/PostUploadFile/")
    Call<UploadFileResponse> uploadFile(@Body RequestBody bytes);

看來你的 stream 是由 form-data 提交的,也就是說 stream 包含了一些不必要的數據,比如提交的 form-data 中的其他數據。 需要注意的一點是 WCF 默認不支持表單數據,我們一般使用第三方庫MultipartParser將數據轉換為完整的文件數據。
這里是下載頁面。
http://antscode.blogspot.com/2009/11/parsing-multipart-form-data-in-wcf.html
在這種情況下,請使用以下代碼段來保存圖像。

public async Task UploadStream(Stream stream)
        {
            //the third-party library.
            MultipartParser parser = new MultipartParser(stream);

            if (parser.Success)
            {
                //absolute filename, extension included.
                var filename = parser.Filename;
                var filetype = parser.ContentType;
                var ext = Path.GetExtension(filename);
                using (var file = File.Create(Path.Combine(HostingEnvironment.MapPath("~/Uploads"), Guid.NewGuid().ToString() +ext)))
                {
                    await file.WriteAsync(parser.FileContents, 0, parser.FileContents.Length);
                }
            }
}

If the stream is the complete binary file, please consider the below code (we use the HTTP header to save the file extension since WCF doesn't allow to contain another parameter in the method signature).

public async Task UploadStream(Stream stream)
        {
            var context = WebOperationContext.Current;
            string filename = context.IncomingRequest.Headers["filename"].ToString();
            string ext = Path.GetExtension(filename);
            using (stream)
            {
                //save the image under the Uploads folder on the server-side(root directory).
                using (var file = File.Create(Path.Combine(HostingEnvironment.MapPath("~/Uploads"), Guid.NewGuid().ToString() + ext)))
                {
                    await stream.CopyToAsync(file);
                }
            }
        }

如果問題仍然存在,請隨時告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM