Upload a file using java web services #651

Open
opened 2017-03-01 17:46:09 +00:00 by eaa007 · 4 comments
eaa007 commented 2017-03-01 17:46:09 +00:00 (Migrated from github.com)

hey guys am stuck in this problem , am using angular 2 as front end and java web services(restful) as back end and am trying to figure out how to upload an image using ng2-file-upload and and save it in hard drive , so my code for angular is same as i the demo but am struggling for the code of jee back end web service method , please help and thanks in advance

hey guys am stuck in this problem , am using angular 2 as front end and java web services(restful) as back end and am trying to figure out how to upload an image using ng2-file-upload and and save it in hard drive , so my code for angular is same as i the demo but am struggling for the code of jee back end web service method , please help and thanks in advance
oliverchuaaus commented 2017-03-07 07:25:44 +00:00 (Migrated from github.com)

hi,

Had the same issue myself, and got it to work via trial and error.
Quick and dirty code sample below. The important bit is the @RequestParam("file").
It isn't mentioned anywhere, AFAIK, that the param is "file",
anything else won't work.
This post method is called for each file, so it doesn't matter if there are multiple files.

@RequestMapping(method = RequestMethod.POST, value="/uploader")
@ResponseBody
public String fileUploader(@RequestParam("file") MultipartFile uploader) throws IOException {
	
		Reader in = new InputStreamReader(uploader.getInputStream());
		String myString = IOUtils.toString(uploader.getInputStream(), "UTF-8");
		Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
		
		for (CSVRecord record : records) {
		    String lastName = record.get(0);
		    String firstName = record.get(1);
		    String value = record.get(2);
		    System.out.println("|"+lastName+"|"+firstName+"|"+value+"|");
		}
	return "file";
}

@RequestMapping(method = RequestMethod.GET, value="/uploader")
@ResponseBody
public String getFileUploader() throws IOException {
	return "something";
}

Oliver

hi, Had the same issue myself, and got it to work via trial and error. Quick and dirty code sample below. The important bit is the @RequestParam("file"). It isn't mentioned anywhere, AFAIK, that the param is "file", anything else won't work. This post method is called for each file, so it doesn't matter if there are multiple files. @RequestMapping(method = RequestMethod.POST, value="/uploader") @ResponseBody public String fileUploader(@RequestParam("file") MultipartFile uploader) throws IOException { Reader in = new InputStreamReader(uploader.getInputStream()); String myString = IOUtils.toString(uploader.getInputStream(), "UTF-8"); Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in); for (CSVRecord record : records) { String lastName = record.get(0); String firstName = record.get(1); String value = record.get(2); System.out.println("|"+lastName+"|"+firstName+"|"+value+"|"); } return "file"; } @RequestMapping(method = RequestMethod.GET, value="/uploader") @ResponseBody public String getFileUploader() throws IOException { return "something"; } Oliver
liyakhatalikhan commented 2017-03-17 03:14:58 +00:00 (Migrated from github.com)

I dont think the request param is file.
Required CommonsMultipartFile parameter 'file' is not present
tried it with multipartfile as well.

@PostMapping("/avatarImage")
@Timed
public ResponseEntity avatarImage(@RequestParam("file") CommonsMultipartFile file) throws URISyntaxException {

I dont think the request param is file. Required CommonsMultipartFile parameter 'file' is not present tried it with multipartfile as well. @PostMapping("/avatarImage") @Timed public ResponseEntity<ImageDTO> avatarImage(@RequestParam("file") CommonsMultipartFile file) throws URISyntaxException {
liyakhatalikhan commented 2017-03-19 17:48:27 +00:00 (Migrated from github.com)

i have a work around to upload the files as base64.

in fileuploader.class.js update the following.

FileUploader.prototype._xhrTransport = function (item) {
    var _this = this;
    var xhr = item._xhr = new XMLHttpRequest();
    var sendable;
    this._onBeforeUploadItem(item);
    // todo
    /*item.formData.map(obj => {
     obj.map((value, key) => {
     form.append(key, value);
     });
     });*/
    if (typeof item._file.size !== 'number') {
        throw new TypeError('The file specified is no longer valid');
    }
    if (!this.options.disableMultipart) {
        sendable = new FormData();
        this._onBuildItemForm(item, sendable);
        sendable.append(item.alias, item._file, item.file.name);
        
        if (this.options.additionalParameter !== undefined) {
            Object.keys(this.options.additionalParameter).forEach(function (key) {
                sendable.append(key, _this.options.additionalParameter[key]);
            });
        }
    }
    else {
        sendable = item._file;
    }
    xhr.upload.onprogress = function (event) {
        var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
        _this._onProgressItem(item, progress);
    };
    xhr.onload = function () {
        var headers = _this._parseHeaders(xhr.getAllResponseHeaders());
        var response = _this._transformResponse(xhr.response, headers);
        var gist = _this._isSuccessCode(xhr.status) ? 'Success' : 'Error';
        var method = '_on' + gist + 'Item';
        _this[method](item, response, xhr.status, headers);
        _this._onCompleteItem(item, response, xhr.status, headers);
    };
    xhr.onerror = function () {
        var headers = _this._parseHeaders(xhr.getAllResponseHeaders());
        var response = _this._transformResponse(xhr.response, headers);
        _this._onErrorItem(item, response, xhr.status, headers);
        _this._onCompleteItem(item, response, xhr.status, headers);
    };
    xhr.onabort = function () {
        var headers = _this._parseHeaders(xhr.getAllResponseHeaders());
        var response = _this._transformResponse(xhr.response, headers);
        _this._onCancelItem(item, response, xhr.status, headers);
        _this._onCompleteItem(item, response, xhr.status, headers);
    };
    xhr.open(item.method, item.url, true);
    xhr.withCredentials = item.withCredentials;
    if (this.options.headers) {
        for (var _i = 0, _a = this.options.headers; _i < _a.length; _i++) {
            var header = _a[_i];
            xhr.setRequestHeader(header.name, header.value);
        }
    }
    if (item.headers.length) {
        for (var _b = 0, _c = item.headers; _b < _c.length; _b++) {
            var header = _c[_b];
            xhr.setRequestHeader(header.name, header.value);
        }
    }
    if (this.authToken) {
        xhr.setRequestHeader(this.authTokenHeader, 'Bearer ' +this.authToken);
    }
    /* Updated the below lines*/
    if (!this.options.disableMultipart) {
     var reader = new FileReader();
	   reader.readAsDataURL(item._file);
	   reader.onload = function () {
	   		var base64Data = reader.result;
        	sendable.append("image", base64Data);
        	xhr.send(sendable);
        }
    }
    else {
    	xhr.send(sendable);
    }
    
    this._render();
};
i have a work around to upload the files as base64. in fileuploader.class.js update the following. FileUploader.prototype._xhrTransport = function (item) { var _this = this; var xhr = item._xhr = new XMLHttpRequest(); var sendable; this._onBeforeUploadItem(item); // todo /*item.formData.map(obj => { obj.map((value, key) => { form.append(key, value); }); });*/ if (typeof item._file.size !== 'number') { throw new TypeError('The file specified is no longer valid'); } if (!this.options.disableMultipart) { sendable = new FormData(); this._onBuildItemForm(item, sendable); sendable.append(item.alias, item._file, item.file.name); if (this.options.additionalParameter !== undefined) { Object.keys(this.options.additionalParameter).forEach(function (key) { sendable.append(key, _this.options.additionalParameter[key]); }); } } else { sendable = item._file; } xhr.upload.onprogress = function (event) { var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0); _this._onProgressItem(item, progress); }; xhr.onload = function () { var headers = _this._parseHeaders(xhr.getAllResponseHeaders()); var response = _this._transformResponse(xhr.response, headers); var gist = _this._isSuccessCode(xhr.status) ? 'Success' : 'Error'; var method = '_on' + gist + 'Item'; _this[method](item, response, xhr.status, headers); _this._onCompleteItem(item, response, xhr.status, headers); }; xhr.onerror = function () { var headers = _this._parseHeaders(xhr.getAllResponseHeaders()); var response = _this._transformResponse(xhr.response, headers); _this._onErrorItem(item, response, xhr.status, headers); _this._onCompleteItem(item, response, xhr.status, headers); }; xhr.onabort = function () { var headers = _this._parseHeaders(xhr.getAllResponseHeaders()); var response = _this._transformResponse(xhr.response, headers); _this._onCancelItem(item, response, xhr.status, headers); _this._onCompleteItem(item, response, xhr.status, headers); }; xhr.open(item.method, item.url, true); xhr.withCredentials = item.withCredentials; if (this.options.headers) { for (var _i = 0, _a = this.options.headers; _i < _a.length; _i++) { var header = _a[_i]; xhr.setRequestHeader(header.name, header.value); } } if (item.headers.length) { for (var _b = 0, _c = item.headers; _b < _c.length; _b++) { var header = _c[_b]; xhr.setRequestHeader(header.name, header.value); } } if (this.authToken) { xhr.setRequestHeader(this.authTokenHeader, 'Bearer ' +this.authToken); } /* Updated the below lines*/ if (!this.options.disableMultipart) { var reader = new FileReader(); reader.readAsDataURL(item._file); reader.onload = function () { var base64Data = reader.result; sendable.append("image", base64Data); xhr.send(sendable); } } else { xhr.send(sendable); } this._render(); };
sazimi commented 2017-08-28 16:38:46 +00:00 (Migrated from github.com)

Any plan to add the official support for 'base64Data' files?

Any plan to add the official support for 'base64Data' files?
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: dc/ng2-file-upload#651