I'm creating a web app using Java servlets and JSPs and I want to create an upload form in JSP for my clients to be able to upload and download stuff. I'm using Cloud Storage and my default bucket to upload stuff.
I followed Google's tutorial on Reading and Writing to Google Cloud Storage.
This is my Servlet:
public class Create extends HttpServlet {
public static final boolean SERVE_USING_BLOBSTORE_API = false;
private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
.initialRetryDelayMillis(10)
.retryMaxAttempts(10)
.totalRetryPeriodMillis(15000)
.build());
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
GcsFilename fileName = getFileName(req);
if (SERVE_USING_BLOBSTORE_API) {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
BlobKey blobKey = blobstoreService.createGsBlobKey(
"/gs/" + fileName.getBucketName() + "/" + fileName.getObjectName());
blobstoreService.serve(blobKey, resp);
} else {
GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(fileName, 0, BUFFER_SIZE);
copy(Channels.newInputStream(readChannel), resp.getOutputStream());
}
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
GcsFileOptions instance = GcsFileOptions.getDefaultInstance();
GcsFilename fileName = getFileName(req);
GcsOutputChannel outputChannel;
outputChannel = gcsService.createOrReplace(fileName, instance);
copy(req.getInputStream(), Channels.newOutputStream(outputChannel));
}
private GcsFilename getFileName(HttpServletRequest req) {
String[] splits = req.getRequestURI().split("/", 4);
if (!splits[0].equals("") || !splits[1].equals("gcs")) {
throw new IllegalArgumentException("The URL is not formed as expected. " +
"Expecting /gcs/<bucket>/<object>");
}
return new GcsFilename(splits[2], splits[3]);
}
private void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} finally {
input.close();
output.close();
}
}
}
I can upload and download successfully, but only text and not real files like images, pdfs, etc., which is my problem.
This tutorial is for reading and writing text but i want to upload real files. As you can see from my jsp the enctype is "text/plain":
<form action="/index.html" enctype="text/plain" method="get" name="putFile" id="putFile">
<div>
Bucket: <input type="text" name="bucket" />
File Name: <input type="text" name="fileName" />
<br /> File Contents: <br />
<textarea name="content" id="content" rows="3" cols="60"></textarea>
<br />
<input type="submit" onclick='uploadFile(this)' value="Upload Content" />
</div>
</form>
I tried to change it to "multipart/form-data" and put a
<input name="content" id="content" type="file">
but this does not upload the real file only the fake path of the file.
And I want to know how to upload real files, any help would be appreciated.
Here is one example on how to upload blobs to Cloud Storage:
First you initialize the storage with these lines:
private static Storage storage = null;
// [START init]
static {
storage = StorageOptions.getDefaultInstance().getService();
}
// [END init]
You may change the code to accept different file extensions according to your needs on the getImageUrl method in the line String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
/**
* Extracts the file payload from an HttpServletRequest, checks that the file extension
* is supported and uploads the file to Google Cloud Storage.
*/
public String getImageUrl(HttpServletRequest req, HttpServletResponse resp,
final String bucket) throws IOException, ServletException {
Part filePart = req.getPart("file");
final String fileName = filePart.getSubmittedFileName();
String imageUrl = req.getParameter("imageUrl");
// Check extension of file
if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
final String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
for (String s : allowedExt) {
if (extension.equals(s)) {
return this.uploadFile(filePart, bucket);
}
}
throw new ServletException("file must be an image");
}
return imageUrl;
}
Here a timestamp is appended in the filename which can be a good idea if you want to make the filename unique.
/**
* Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
* environment variable, appending a timestamp to end of the uploaded filename.
*/
#SuppressWarnings("deprecation")
public String uploadFile(Part filePart, final String bucketName) throws IOException {
DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
DateTime dt = DateTime.now(DateTimeZone.UTC);
String dtString = dt.toString(dtf);
final String fileName = filePart.getSubmittedFileName() + dtString;
// the inputstream is closed by default, so we don't need to close it here
BlobInfo blobInfo =
storage.create(
BlobInfo
.newBuilder(bucketName, fileName)
// Modify access list to allow all users with link to read file
.setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
.build(),
filePart.getInputStream());
// return the public download link
return blobInfo.getMediaLink();
}
In this documentation you'll find more details: https://cloud.google.com/java/getting-started/using-cloud-storage#uploading_blobs_to_cloud_storage
The complete code for this example is in github: https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/bookshelf/3-binary-data/src/main/java/com/example/getstarted/util/CloudStorageHelper.java
I found a solution.
This is my JSP:
<form action="/create" enctype="multipart/form-data" method="post" name="putFile" id="putFile">
<div>
File Name: <input type="text" name="fileName" />
<br /> File Contents: <br />
<input type="submit" value="Upload Content" />
</div>
</form>
When i submit the form, it goes into this Servlet:
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Part filePart = req.getPart("content"); /*Get file from jsp*/
/*Get file name of file from jsp*/
String name = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
GcsFileOptions instance = GcsFileOptions.getDefaultInstance();
GcsFilename fileName = new GcsFilename(BUCKET_NAME, name);
GcsOutputChannel outputChannel;
outputChannel = gcsService.createOrReplace(fileName, instance);
/*Pass the file to copy function, wich uploads the file to cloud*/
copy(filePart.getInputStream(), Channels.newOutputStream(outputChannel));
req.getRequestDispatcher("download.jsp").forward(req, resp);
}
private GcsFilename getFileName(HttpServletRequest req) {
String[] splits = req.getRequestURI().split("/", 4);
if (!splits[0].equals("") || !splits[1].equals("gcs")) {
throw new IllegalArgumentException("The URL is not formed as expected. " +
"Expecting /gcs/<bucket>/<object>");
}
return new GcsFilename(splits[2], splits[3]);
}
private void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} finally {
input.close();
output.close();
}
}
Related
I would like to upload a zip file in Angular, and send the zip file to the backend (java/micronaut) and extract it there. There is already some implementation done, the backend receives the zip file eg. "File.zip", however it can't find the file
Is it necessary to add the complete Path of the file? if yes, how I can get it? from the Frontend or Backend?
Angular:
<div style="width: 0px; height: 0px; overflow: hidden;">
<input #fileUploadInput type="file" style="visibility: hidden" accept=".zip"
(change)="uploadFile($event.target.files)">
uploadFile(files: FileList) {
if (!files || files.length !== 1) {
return;
}
this.orderService.importFile(this.order.id, files[0], this.appComponent, success => {
if (success) {
this.loadOrder(this.order.id);
}
});
}
Backend (Micronaut) Controller
#Post("/order/import/file/{orderId}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public HttpResponse importOrderFile(
CompletedFileUpload fileUpload,
#Parameter(String orderId) {
try {
service.orderService.importOrder(orderId, fileUpload.getInputStream(), fileUpload.getFilename());
return HttpResponse.ok();
}
catch (IOException e) {
return HttpResponse.badRequest("Bad input");
}
}
Service
public void importOrder(String orderId, InputStream in, String fileName) throws IOException {
Set<String> extractedFiles = getUncompressedFiles(fileName);
Iterator<String> itr = extractedFiles.iterator();
while(itr.hasNext()){
//...
}
}
public Set<String> getUncompressedFiles(String fileZip) throws IOException {
Set<String> files = new HashSet<>();
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zipIn.getNextEntry();
while (zipEntry != null) {
String zipEntryName = zipEntry.getName();
String fileName = zipEntryName.substring(zipEntryName.indexOf("order-nr"));
files.add(fileName);
zipIn.closeEntry();
zipEntry = zipIn.getNextEntry();
}
zipIn.close();
return files;
}
You are making the assumption the file is on the filesystem and that its name is the name of the stored file.
Depending on your configuration, the file may only exist in memory. For cases when the file is stored on the file system, its name does not match what is returned from fileUpload.getFilename(). That method returns what the client reported the name of the file is.
Your getUncompressedFiles(String fileZip) method should instead pass the input stream of the file and it should be used instead of new FileInputStream(fileZip)
html:
<form action="/upload" method="post" enctype="multipart/form-data">
<input name="upload" type="file">
<input type="submit" value="upload">
</form>
servlet3:
#WebServlet("/upload")
#MultipartConfig
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("upload");
String header = filePart.getHeader("Content-Disposition");
String filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
System.out.println(filename);
InputStream in = filePart.getInputStream();
OutputStream out = new FileOutputStream("D:/temp.png");
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
in this way, I can upload file successfully, but I'd like to deal it in struts2 the same way, code block below:
public void newTask() throws Exception {
Part filePart = request.getPart("file");
String header = filePart.getHeader("Content-Disposition");
String _filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
InputStream in = filePart.getInputStream();
OutputStream out = new FileOutputStream("D://temp.png");
StreamUtils.copy(in, out);
}
but it doesn't work, I can't get anything from Part, it throw NullPointException, what should I do to change my code or it can't work in strut2 use the same way connect file with servlet3?
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
<body>
<form method="post" action="DemoServlet" enctype="multipart/form-data" name="form1">
<input type="file" name="file" />
Image_Name:<input type="text" name="file"/>
<input type="submit" value="Go"/>
</form>
</body>
this is my index.jsp page.
This Servlet is DemoServlet when user click on submit button it will go here.while in jsp page suppose Image_Name given by user is IPL and actual name of image is funny.jpg then while saving the image it should store as IPL.png,here i'm able to upload image correctly with funny.jpg,but i need to save image as given name in text field of index.jsp page
public class DemoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Date date = new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator itr = upload.getItemIterator(request);
while (itr.hasNext()) {
FileItemStream item = itr.next();
if (item.isFormField()) {
String fieldname = item.getFieldName();
InputStream is = item.openStream();
byte[] b = new byte[is.available()];
is.read(b);
String value = new String(b);
response.getWriter().println(fieldname + ":" + value + "</br>");
} else {
String TempPath = getServletContext().getRealPath("");
String path = TempPath.substring(0, TempPath.indexOf("build"));
if (FileUpload.processFile(path, item)) {
out.println("File Uploaded on:" + date + "<br>");
response.getWriter().println("Image Upload Successfully");
} else {
response.getWriter().println("Failed.....Try again");
}
}
}
} catch (FileUploadException fue) {
fue.printStackTrace();
}
}
}
}
and this is java class
public class FileUpload {
public static boolean processFile(String path, FileItemStream item) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
Could anybody guide me how to change this dynamically.Thanks in advance.
I don't know how Servlet's and the like work however i can give you a rundown of what you need to do.
In DemoServlet you need to take in the input of the Image_Name field and make that one of your parameters of FileUpload
public static boolean processFile(String path, FileItemStream item, String fileName){
//Method Code
}
Because currently your processFile method is taking the name of the file from your FileItemStream. You need to change it from that to your actual fileName
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
to
File savedFile = new File(f.getAbsolutePath() + File.separator + fileName + ".png");
You can change the name of image in your java class code.
public class FileUpload {
public static boolean processFile(String path, FileItemStream item , String name) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName()); // instead of item.getName() you can give your name.
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
you will have to pass the file name in the method.
instead of item.getName() you can give your name.
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
System.out.println("In >>>>>>>>>>>>>>> :: "+fileItems);
while(i.hasNext()){
FileItem fi = (FileItem) i.next();
System.out.println("Val <<<<>>>>>>:: "+fi);
if(fi.isFormField()){
String fieldName = fi.getFieldName();
String val = fi.getString();
System.out.println(fieldName+" :: Val :: "+val);
}else{
String fileName = fi.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root+"/uploads");
if (!path.exists()) {
boolean status = path.mkdir();
}
File uploadFile = new File(path+"/"+fileName);
fi.write(uploadFile);
}
In the code above you can change the file name at any time and it will automatically save with this name.
//How does not work in this way?Please tell me another way.
import java.io.File;
public class RenameFileExample {
public static void main(String[] args)
{
File oldfile =new File("oldfile.txt");
File newfile =new File("newfile.txt");
File file = new File("oldfilename.png");
file.renameTo(new File("newfilename.png"));
System.out.println("Rename To:"+file.getName());
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}
I am uploading an excel file from one jsp page. below is the code.
<form action="Upload.jsp" enctype="MULTIPART/FORM-DATA" method=post >
<input type="file" name="filename" />
<input type="submit" value="Upload" />
</form>
But how to get the excel file in the next page(Upload.jsp)?
I was using but getting error in the second line.
InputStream file = request.getInputStream();
POIFSFileSystem myFileSystem = new POIFSFileSystem(file );
Then how to get the excel file from the request?
You are getting a Multipart/form-data on the request from which you need to extract the Part containing your file bytes.
The simplest to do this is to use Apache Commons Fileupload
http://commons.apache.org/fileupload/
Create a FileUploader
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.;
import java.io.;
public class FileUploader
{
private static ServletFileUpload uploader;
private FileUploader()
{
}
public static synchronized ServletFileUpload getservletFileUploader(String tempDir, int maxSizeInMB)
{
if(uploader == null)
{
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);
factory.setRepository(new File(tempDir));
uploader = new ServletFileUpload(factory);
uploader.setFileSizeMax(maxSizeInMB * 1024 * 1024);
}
return uploader;
}
}
Then use it when processing the request
protected MultiPartFormData handleMultiPartRequest(HttpServletRequest request)
throws FileSizeLimitExceededException
{
if(!isMultipartRequest(request))
return null;
ServletFileUpload upload = FileUploader.getservletFileUploader(tempDir, 50);
MultiPartFormData data = new MultiPartFormData();
try
{
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items)
{
if(item.isFormField())
{
data.getParameters().put(item.getFieldName(), item.getString());
}
else
{
String filename = item.getName();
//Internet explorer and firefox will send the file name differently
//Internet explorer will send the entire path to the file name including
//the backslash characters etc ... we should strip it down
//THIS IS HACKY
if(filename.indexOf("\\") != -1)
{
int index = filename.lastIndexOf("\\");
filename = filename.substring(index + 1);
}
if(filename == null || filename.equals(""))
{
//do nothing
}
else
{
String randomFileName = (new RandomGUID()).toString() + getFileExtension(filename);
File uploadFile = new File(uploadDir + File.separator + randomFileName);
item.write(uploadFile);
}
}
}
}
catch(FileSizeLimitExceededException e)
{
throw e;
}
catch(Exception e)
{
e.printStackTrace();
}
return data;
}
For your reference ... MultiPartForm data looks like
import java.util.Hashtable;
import java.util.ArrayList;
public class MultiPartFormData {
private ArrayList<Integer> fids;
private Hashtable<String, String> parameters;
public MultiPartFormData()
{
this.fids = new ArrayList<Integer>();
this.parameters = new Hashtable<String, String>();
}
public ArrayList<Integer> getFids() {
return fids;
}
public void setFids(ArrayList<Integer> fids) {
this.fids = fids;
}
public Hashtable<String, String> getParameters() {
return parameters;
}
public void setParameters(Hashtable<String, String> parameters) {
this.parameters = parameters;
}
}
Well guys, thanks for all the reply. But I have resolved the problem with below process.
Inside JSP:
<form action="/upload.do" enctype="MULTIPART/FORM-DATA" method=post >
<input type="file" name="file" id="file" size=25/>
<input type="submit" value="Upload" />
</form>
Created a form bean: inside that
private FormFile file;
public void setFile(FormFile file) {
this.file = file;
}
public FormFile getFile() {
return file;
}
In action class upload:
FileUploadForm uploadForm = (FileUploadForm) form;
FormFile file = uploadForm.getFile();
InputStream stream = file.getInputStream();
POIFSFileSystem fsFileSystem = new POIFSFileSystem(stream);
//
rest of code for reading the excel
//
Now its working fine.
thanks for your answer, but using an InputStream instead of using getBody(...) does also not work. The code below returns the same result as the one from my original post.
final InputStream inStream = fileUploadInput.getFormDataPart(searchedInput, InputStream.class, null);
// get bytes
final byte[] inBytes = new byte[1024];
final ByteArrayOutputStream outBytes = new ByteArrayOutputStream(inBytes.length);
int length = 0;
while((length = inStream.read(inBytes)) >= 0) {
outBytes.write(inBytes, 0, length);
}
final byte[] rawInput = outBytes.toByteArray();
// get Encoding
final String asciiInput = new String(rawInput, ASCII);
final String utf8 = new String(rawInput, UTF8);
final String isoLatin1 = new String(rawInput, ISO8859_1);
log.info("ASCII: " + ascii);
log.info("UTF8: " + utf8);
log.info("ISOLATIN1: " + isoLatin1);
return utf8;
ORIGINAL POST:
I want to upload UTF-8 encoded XML files using the HTML form below and read it on the server using a RESTEasy MultipartFormDataInput, and the Java code shown below. On the server side I seem to be getting the content of the file(s) ASCII encoded, independent of the actual encoding of the uploaded files (which is UTF-8) (accessing it the way described below). All characters not part of the ASCII character set are are being replaced by ?. How can I get 'text/xml' as UTF-8 from a 'multipart/form-data' request with RESTeasy? (I know it is possible to write a PreProcessor - Interceptor and get the raw bytes there, but I can't use this approach in my application).
Upload Form:
<html>
<body>
<h1>JAX-RS Upload Form</h1>
<form action="http://.../upload" method="POST" enctype="multipart/form-data">
<p>Select a file : <input type="file" name="upload"/></p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
Resource class:
#Path("/upload")
#POST
#Consumes("multipart/form-data")
public Response createUploadTemplate(
#Context HttpServletRequest req,
MultipartFormDataInput formInput) {
try {
final String templateXml = getInput("upload", formInput);
//...
} catch (Exception e) {
//...
}
}
private static String getInput(final String searchedInput, final MultipartFormDataInput fileUploadInput) throws BadRequestException, IOException {
try {
final Map<String, List<InputPart>> inputToInputPart = fileUploadInput.getFormDataMap();
if(inputToInputPart.containsKey(searchedInput)) {
final StringBuilder builder = new StringBuilder();
final List<InputPart> inputParts = inputToInputPart.get(searchedInput);
for(InputPart inputPart : inputParts) {
builder.append(inputPart.getBody(String.class,null));
}
return builder.toString();
} else {
throw new BadRequestException("The form send with the request does not contain an input element " + searchedInput + ".");
}
} catch(Exception e) {
throw new BadRequestException("The file upload failed.", e);
}
}
MessageBodyReader:
#Provider
#Consumes ("text/xml")
public class XmlStringReader implements MessageBodyReader<String> {
private static Logger log = LoggerFactory.getLogger(UploadedXmlStringReader.class);
private static final String ASCII = "ASCII";
private static final String ISO8859_1 = "ISO8859_1";
private static final String UTF8 = "UTF8";
#Override
public boolean isReadable(final Class<?> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType) {
boolean result = type.equals(String.class) && MediaType.TEXT_XML_TYPE.equals(mediaType);
log.info(MessageFormat.format("{0} == String.class && MediaType.TEXT_XML_TYPE == {1}: {2}", type, mediaType, result));
return result;
}
#Override
public String readFrom(final Class<String> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String, String> httpHeaders,
final InputStream entityStream) throws IOException, WebApplicationException {
final byte[] inBytes = new byte[1024];
final ByteArrayOutputStream outBytes = new ByteArrayOutputStream(inBytes.length);
int length = 0;
while((length = entityStream.read(inBytes)) >= 0) {
outBytes.write(inBytes, 0, length);
}
final byte[] rawInput = outBytes.toByteArray();
final String ascii = new String(rawInput, ASCII);
final String utf8 = new String(rawInput, UTF8);
final String isoLatin1 = new String(rawInput, ISO8859_1);
log.info("ASCII: " + ascii);
log.info("UTF8: " + utf8);
log.info("ISOLATIN1: " + isoLatin1);
return utf8;
}
}
When no charset is defined in the content-type header of your HTTP request, resteasy assumes 'charset=US-ASCII'.
See org.jboss.resteasy.plugins.providers.multipart.InputPart:
/**
* If there is a content-type header without a charset parameter, charset=US-ASCII
* is assumed.
* <p>
* This can be overwritten by setting a different String value in
* {#link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)}
* with this ("resteasy.provider.multipart.inputpart.defaultCharset")
* String`enter code here` as key. It should be done in a
* {#link org.jboss.resteasy.spi.interception.PreProcessInterceptor}.
* </p>
*/
So, as a work-around you can do the following:
#Provider
#ServerInterceptor
public class CharsetPreProcessInterceptor implements PreProcessInterceptor {
#Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException {
request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, "charset=UTF-8");
return null;
}
}
I generally would not rely on the getBody method on InputPart. You can actually get each part as a raw input stream and read the data in yourself. Rather than relying on the framework to convert the content to a String.