FileUpload with Rest on Apache Wicket

Synopsis so far

I came across a situation where I want to implement FileUpload processing via JavaScript in Nanika made with Apache Wicket.

Rest in Wicket is wicketstuff-restannotations. There is an ancestor who also posted an article on Qiita, and you can see how to use it by looking at the linked document, but a sample of FileUpload Is not found.

That's why I decided to leave a note that it seems to be a power technique for the time being, but it worked with this.

Version

Implementation

Caller. Come on. I don't think it's JQuery anymore, but it's Wicket.

test.html


<!DOCTYPE html>
<html>
<body>
<input type="file" id="file-select" style="display:none">
<button id="file-button">File selection</button>
<script>
$('#file-button').click(function(e) {
  $("#file-select").click();
});
$("#file-select").change(function(e) {
  var file = e.target.files;
  if(file.length > 0) {
    var form = new FormData();
    form.append('image', file[0]);
    var settings = {
      "async": false,
      "crossDomain": false,
      "url": "fileUpload",
      "method": "POST",
      "dataType": "text",
      "processData": false,
      "contentType": false,
      "data": form
    }
    $.ajax(settings).done(function (response) {
      if(result.success) {
        alert(response);
      }
    });
  }
});
</script>
</body>
</html>

RestResource。 Is it the immediate goal to get the FileItem of FileUpload here? I think that the response in JSON is normal, but I omit that part. It doesn't matter, but I'm not sure why Abstract Rest Resource is a generic type.

FileUploadResource.java


package yamane.rest;

import org.apache.commons.fileupload.FileItem;
import org.wicketstuff.rest.annotations.MethodMapping;
import org.wicketstuff.rest.annotations.parameters.RequestBody;
import org.wicketstuff.rest.contenthandling.mimetypes.RestMimeTypes;
import org.wicketstuff.rest.resource.AbstractRestResource;
import org.wicketstuff.rest.utils.http.HttpMethod;

public class FileUploadResource extends AbstractRestResource<FileUploadSerialDeserial> {

  public FileUploadResource() {
    super(new FileUploadSerialDeserial());
  }

  @MethodMapping(
    value = "/fileUpload",
    httpMethod = HttpMethod.POST,
    produces = RestMimeTypes.TEXT_PLAIN
  )
  public String saveImage(@RequestBody FileItem item) {
    //If you can get FileItem, you win!
    return item.getFieldName();
  }
}

The part of the liver, IWebSerialDeserial. Well, I just fetch HttpServletRequest and parse it with FileUpload. It is quite appropriate except for the corresponding processing. Corresponding processing is also reasonably appropriate. It doesn't matter, but what about the name SerialDeserial?

FileUploadSerialDeserial.java


package yamane.rest;

import java.io.File;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.http.WebResponse;
import org.wicketstuff.rest.contenthandling.IWebSerialDeserial;

public class FileUploadSerialDeserial implements IWebSerialDeserial {

  DiskFileItemFactory factory = new DiskFileItemFactory();

  FileUploadSerialDeserial() {
    ServletContext context = WebApplication.get().getServletContext();
    File repository = (File) context.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
  }

  @Override
  public void objectToResponse(Object str, WebResponse response, String mimeType) throws WicketRuntimeException {
    ServletResponse sResponse = (ServletResponse) response.getContainerResponse();
    sResponse.setCharacterEncoding("UTF-8");
    response.write((CharSequence) str);
  }

  @Override
  @SuppressWarnings("unchecked")
  public <T> T requestToObject(
    WebRequest wRequest,
    Class<T> argClass,
    String mimeType) throws WicketRuntimeException {
    try {
      ServletWebRequest sRequest = (ServletWebRequest) wRequest;
      HttpServletRequest request = sRequest.getContainerRequest();
      ServletFileUpload fileUpload = new ServletFileUpload(factory);
      List<FileItem> items = fileUpload.parseRequest(request);
      return !items.isEmpty() ? (T) items.get(0) : null;
    } catch (FileUploadException e) {
      throw new WicketRuntimeException(e);
    }
  }

  @Override
  public boolean isMimeTypeSupported(String mimeType) {
    return true;
  }
}

Up to here for this time

So, I was able to get the file via JavaScript safely. It's a rough article, but please forgive me for taking notes.

Recommended Posts

FileUpload with Rest on Apache Wicket
Invalid lambda deserialization on Apache Wicket 8 Lambda
Build REST API with Apache2 + Passenger + Sinatra.
Using templates on the classpath with Apache Velocity
Hello World (REST API) with Apache Camel + Spring Boot 2
Apache2 on Ubuntu20.04 LTS
Repeated sample with Apache Freemarker
Create XML-RPC API with Wicket
Start Apache Solr with Embedded.
Avoid serializing pages with Wicket
CSV output with Apache Commons CSV
Access Apache Kafka with Micronaut
Install Apache on CentOS on VirtualBox
I tried using Apache Wicket
REST API testing with REST Assured
Manipulate Excel with Apache POI
Prepare a transcendentally simple PHP & Apache environment on Mac with Docker