[Notes] [JAVA] [C#] Web service return file

[Notes] [JAVA] [C#] Web service return file

透過API向PLM file maneger獲取檔案,再經過web service return byte array到C#處理。


 

【PART I】JAVA

public byte[] PLMDownloadAPI(String FormNum, String FileID) throws IOException
{
	IAgileSession session=(IAgileSession) new AgilUtil().connect();
	IDeclaration dr;
	InputStream stream = null;
    String FileName = "";
	byte[] bytes = null;
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	
	try {
		dr = (IDeclaration)session.getObject(IDeclaration.OBJECT_TYPE, FormNum);
		ITable tab_attachment = dr.getAttachments();
		ITwoWayIterator tab_attachment_r = tab_attachment.getTableIterator();
		while (tab_attachment_r.hasNext()){
			IRow row=(IRow) tab_attachment_r.next();
			
			if (row.getId().toString().equals(FileID)) {
				System.out.println(row.getName());
				FileName = row.getName();
				if (((IAttachmentFile)row).isSecure())
				stream = ((IAttachmentFile)row).getFile();
				bytes = IOUtils.toByteArray(stream);
			}
		}	
	} catch (APIException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return bytes;
}

【PART II】C#

<%@ WebHandler Language="C#" Class="PLMDownload" %>

using System;
using System.Web;
using System.Web.Script.Serialization;
using Models;
using System.IO;
using SupplierWeb.PLM_Service;

public class PLMDownload : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string json = string.Empty;
        returnObject PLMJSON = new returnObject(); //PLM JSONStr return object
        var serializer = new JavaScriptSerializer();
        byte[] stream;

        try
        {
            if (context.Request.RequestType == "POST")
            {
                using (var reader = new StreamReader(context.Request.InputStream))
                {
                    json = reader.ReadToEnd();
                }

                if (!string.IsNullOrEmpty(json))
                {
                    var PLMDownloadParameter = serializer.Deserialize<PLMDownloadParameter>(json);
                    using (AndyTestClient wcf = new AndyTestClient())
                    {
                        stream = wcf.PLMDownloadAPI(PLMDownloadParameter.FormNum,PLMDownloadParameter.FileID);
                    }

                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AddHeader("Content-Disposition", "attachment;");
                    context.Response.BinaryWrite(stream);
                    context.Response.Flush();
                }
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(new JavaScriptSerializer().Serialize(
            new
            {
                Result = false,
                Message = ex.Message
            }));
        }
        context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

【PART III】JavaScript

DownloadFile: function (FileID,FileName) {
    v_this = this;
    var Url = 'handler/PLMDownload.ashx';
    var v_obj = {
        FormNum: v_this.FormNum,
        FileID: FileID
    }
    console.log(v_obj);
    this.$http.post(Url, JSON.stringify(v_obj), {
        emulateJSON: true,
        responseType: 'blob'
    })
    .then(res => {
        //console.log(res);
        let url = window.URL.createObjectURL(new Blob([res.data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', FileName)

        document.body.appendChild(link)
        link.click()
        
    }).catch(err => {
        console.log(err);
    })
}

 


Reference

Java InputStream to String

How to download a file using a Java REST service and a data stream

Using REST Services to manage download and upload of files

Save byte array to file [duplicate]

[ASP.NET] C# 點擊按鈕來下載檔案 - download file

如何在 .NET 中序列化和還原序列化 (封送處理和 unmarshal) JSON

StreamReader讀取InputStream注意事項

Http請求。輸入流屬性

[C#] ASP.NET 檔案下載(1) - POST 和 GET 觸發檔案下載

How do I save a stream to a file in C#?

How do I read / convert an InputStream into a String in Java?

Java InputStream转File