Я пытаюсь выполнить загрузку файла с клиента JavaScript на Java-сервер JAX-RS.
Я использую следующую функцию загрузки REST на моем сервере:
@POST
@Produces('application/json')
UploadDto upload(
@Context HttpServletRequest request,
@QueryParam("cookie") String cookie) {
def contentType
byte [] fileBytes
log.debug "upload - cookie: "+cookie
try{
if (request instanceof MultipartHttpServletRequest) {
log.debug "request instanceof MultipartHttpServletRequest"
MultipartHttpServletRequest myrequest = request
CommonsMultipartFile file = (CommonsMultipartFile) myrequest.getFile('file')
fileBytes = file.bytes
contentType = file.contentType
log.debug ">>>>> upload size of the file in byte: "+ file.size
}
else if (request instanceof SecurityContextHolderAwareRequestWrapper) {
log.debug "request instanceof SecurityContextHolderAwareRequestWrapper"
SecurityContextHolderAwareRequestWrapper myrequest = request
//get uploaded file inputStream
InputStream inputStream = myrequest.inputStream
fileBytes = IOUtils.toByteArray(inputStream);
contentType = myrequest.getHeader("Content-Type")
log.debug ">>>>> upload size of the file in byte: "+ fileBytes.size()
}
else {
log.error "request is not a MultipartHttpServletRequest or SecurityContextHolderAwareRequestWrapper"
println "request: "+request.class
}
}
catch (IOException e) {
log.error("upload() failed to save file error: ", e)
}
}
На стороне клиента я отправляю файл следующим образом:
var str2ab_blobreader = function(str, callback) {
var blob;
BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder
|| window.BlobBuilder;
if (typeof (BlobBuilder) !== 'undefined') {
var bb = new BlobBuilder();
bb.append(str);
blob = bb.getBlob();
} else {
blob = new Blob([ str ]);
}
var f = new FileReader();
f.onload = function(e) {
callback(e.target.result)
}
f.readAsArrayBuffer(blob);
}
var fileName = "fileName.jpg";
var contentType = "image/jpeg";
if (file.type.toString().toLowerCase().indexOf("png") > -1) {
fileName = "fileName.png";
contentType = "image/png";
}
var xhrNativeObject = new XMLHttpRequest();
var urlParams = ?test=123;
xhrNativeObject.open("post", url + urlParams, true);
xhrNativeObject.setRequestHeader("Content-Type", contentType);
xhrNativeObject.onload = function(event) {
var targetResponse = event.currentTarget;
if ((targetResponse.readyState == 4)
&& (targetResponse.status == 200)) {
var obj = JSON.parse(targetResponse.responseText);
console.log(obj.uploadImageId);
} else {
console.log("fail");
}
}
var buffer = str2ab_blobreader(file, function(buf) {
xhrNativeObject.send(buf);
});
Когда я использую код в своем контроллере Grails, он работал хорошо, но когда я использую его в REST-ресурсе, я всегда получаю: request не является MultipartHttpServletRequest или SecurityContextHolderAwareRequestWrapper
Выход журнала
request: com.sun.proxy.$Proxy58
Отправка файла blob из JavaScript Я использую XMLHttpRequest
, который содержит blob в теле и некоторые параметры запроса.
Как я могу заставить загружать файлы JAX-RS? Как получить некоторые дополнительные параметры запроса с моим POST-запросом?