I am getting server error 500 when trying to upload a file

0 votes

I am trying to upload a file using

Upload upload = uploadService.uploadFile(fileName, fileStream, fileType, description);

 

This is the post body 

--146bdc89009
Content-Disposition: form-data; name="temp2566689044278828576s.png"; filename="temp2566689044278828576s.png"
Content-Type: image/png
Content-Transfer-Encoding: binary
 
����C ..
--146bdc89009
Content-Disposition: form-data; name="name"
Content-Type: text/plain; charset=UTF-8
 
temp2566689044278828576s.png
--146bdc89009
Content-Disposition: form-data; name="type"
Content-Type: text/plain; charset=UTF-8
 
IMAGE
--146bdc89009
Content-Disposition: form-data; name="description"
Content-Type: text/plain; charset=UTF-8
 
wqewer
--146bdc89009--
 
And this is a partial list of  the header  parameters
timeStamp=[2014-06-21T09:36:13.164Z]
User-Agent=[Profile/MIDP-1.0 Confirguration/CLDC-1.0]
SDKName=[J2ME]
Content-Type=[multipart/form-data;boundary=**********]
Accept=[application/json]
signature=[Bgr70TrE9D3tHMFBwdbJIeMj6QA=]
apiKey=[4d1dbd8dbbeee0b9f10e654b426686ecabb6ec09206fc18d6d05b22880919c44]
version=[1.0]
 
 
I keep getting Error 500, internal server error. What is the problem.
 

 

asked Jun 21, 2014 in App42 Cloud API-BaaS by jamesagada (20 points)

1 Answer

0 votes
Hi James,

Can you put complete snippet of your code.? Also, is it coming for specific type of files or are you getting for all files?
answered Jun 21, 2014 by ajay123 (899 points)
I am using only images and i have gotten for files of different sizes.  Code snippets
1. private String saveDataElement(HashMap data, String elementType){
   
    String response ="http://www.testing.com/url";
    if (elementType.equalsIgnoreCase(UploadFileType.IMAGE) ||
            elementType.equalsIgnoreCase(UploadFileType.VIDEO)) {
        //dataelement is a file to be uploaded
        String file = data.get("propertyValue").toString();
        String fileName = file.substring(file.lastIndexOf("/")+1);
        response = App42ServiceHandler.instance().uploadFile(
                fileName,
                file,
                elementType,
                data.get("propertyName").toString());
    }
       
    return response;
}

2. In App42ServiceHandler
    public String uploadFile(String fileName, String filePath, String fileType, String description){
        App42Log.setDebug(true);
        App42Log.debug("upload file "+filePath );
        InputStream fileStream;
        try {
            fileStream = FileSystemStorage.getInstance().openInputStream(filePath);
        }catch(Exception e){
            //failed to open file
            App42Log.debug(e.getMessage());   
            return "";
        }
        try {
            Upload upload = uploadService.uploadFile(fileName, fileStream, fileType, description);
            return ((File) upload.getFileList().elementAt(0)).getUrl();
        }catch (Exception e){
            //some error
            App42Log.debug(e.getMessage());
            return "";
        }
       

    }

3. I have ported the J2ME client to work with codenameone and i use the codenameone multipartrequest to send the file to App42 as in here

    /**
     * Multipart request for all the methods
     *
     * @param name
     * @param file
     * @param queryParams
     * @param postParams
     * @param urlPost
     * @param accept
     *
     * @return string
     *
     * @throws Exception
     *
     */
    public static String multiPartRequest(String name,
            InputStream fileInputStream, String fileName,
            Hashtable queryParams, Hashtable postParams,
            Hashtable headerParams, String urlPost, String accept)
            throws Exception {

        MultipartRequest conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String boundary = "**********";

        int bytesRead, bytesAvailable, bufferSize;

        byte[] buffer;

        int maxBufferSize = 1 * 1024 * 1024;
        urlPost = net.oauth.jme.Util.replace(urlPost, " ", "%20");

        StringBuffer queryString = new StringBuffer("?");
        String apiKey = (String) queryParams.get("apiKey");
        String signature = (String) queryParams.get("signature");
        String timeStamp = (String) queryParams.get("timeStamp");
        String sessionId = (String) queryParams.get("sessionId");
        String adminKey = (String) queryParams.get("adminKey");
        queryParams.remove("apiKey");
        queryParams.remove("signature");
        queryParams.remove("timeStamp");
        queryParams.remove("sessionId");
        queryParams.remove("adminKey");
        // Get all Request parameter and set here
        Enumeration enumKeys = queryParams.keys();
        while (enumKeys.hasMoreElements()) {
            String key = (String) enumKeys.nextElement();
            String value = (String) queryParams.get(key);
            queryString.append(URLEncoder.encode(key) + "="
                    + URLEncoder.encode(value) + "&");
        }

        String urlString = urlPost + queryString;
        String str=null;
        String mimeType = MimeTypes.getInstance().getMimeType(fileName);    

        try {
            // ------------------ CLIENT REQUEST

            // FileInputStream fileInputStream = new FileInputStream(file);

            // open a URL connection to the Servlet
            App42Log.debug(" Upload URL is " + urlString);

            // Open a HTTP connection to the URL

            conn = new MultipartRequest();
            conn.setPost(true);
           
            // Use a post method.

            conn.addRequestHeader("Accept", "application/json");

            Enumeration enumKeysHeader = headerParams.keys();
            while (enumKeysHeader.hasMoreElements()) {
                String key = (String) enumKeysHeader.nextElement();
                String value = (String) headerParams.get(key);
                conn.addRequestHeader(key, value);
            }
            conn.addRequestHeader("User-Agent",
                    "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
            // conn.setRequestProperty("Connection", "Keep-Alive");

            conn.addRequestHeader("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            // conn.setRequestProperty("Content-Type",
            // "application/octet-stream");

                conn.setUrl(urlString);

                            //add the data image

                conn.setPriority(ConnectionRequest.PRIORITY_CRITICAL);


            // read file and write it into form...
            conn.addData(fileName, fileInputStream,FileSystemStorage.getInstance().getLength(fileName)  ,mimeType);    
            conn.setFilename(name, fileName);

            // Put Parameter here


            Enumeration keysParam = postParams.keys();
            int i = 0;
            while (keysParam.hasMoreElements()) {
                i++;
                String key = (String) keysParam.nextElement();
                String value = (String) postParams.get(key);
                conn.addArgument(key,value);

                App42Log.debug(" Setting Param  :" + key + " : " + value);
            }

            NetworkManager.getInstance().addToQueueAndWait(conn);

            // ------------------ read the SERVER RESPONSE
            StringBuffer responseMessage = new StringBuffer();
            responseMessage.append(conn.getResponseData());

            if (conn.getResponseCode() != 200) {

                str = responseMessage.toString();
                // Do Exception Handling for App42
                JSONObject jsonObj = new JSONObject(str);
                int httpErrorCode = Integer.valueOf(
                        jsonObj.getJSONObject("app42Fault").getString(
                                "httpErrorCode")).intValue();
                int appErrorCode = Integer.valueOf(
                        jsonObj.getJSONObject("app42Fault").getString(
                                "appErrorCode")).intValue();

                if (httpErrorCode == 404) {
                    throw new App42NotFoundException(str, httpErrorCode,
                            appErrorCode);
                } else if (httpErrorCode == 400) {
                    throw new App42BadParameterException(str, httpErrorCode,
                            appErrorCode);
                } else if (httpErrorCode == 401) {
                    throw new App42SecurityException(str, httpErrorCode,
                            appErrorCode);
                } else if (httpErrorCode == 413) {
                    throw new App42LimitException(str, httpErrorCode, 1413);
                } else if (httpErrorCode == 500) {
                    throw new App42Exception(str, httpErrorCode, appErrorCode);
                } else {
                    throw new App42Exception(
                            "We are sorry something has gone wrong on our side",
                            500, 1500);
                }

            }

        } catch (Exception ex) {
            App42Log.debug("From ServletCom CLIENT REQUEST:" + ex);
            throw ex;
        } finally {
            fileInputStream.close();

            dos.close();
            //conn.close();
        }

        return str;

    }
I will check this code, make sure you done have any null value method call like filename, stream etc.
Hi James,

Kindly find the sample link below for upload file in J2ME and let me know if it will work.
https://github.com/NareshDShephertz/App42_J2meFile_Upload
Thanks.
Download Widgets
Welcome to ShepHertz Product line forum, where you can ask questions and receive answers from the community. You can also reach out to us on support@shephertz.com
...