Get size of attachment in email - java

I don't have much experience with JAVA mail programming and I need help with one task.
I have this code (this is a part of all code where I load attachments; if you need to see whole code, I can send) and I need to write an attachment size to a new variable
I searched the web and found out that size could be get from getSize() function or by counting bytes of file but I don't know how can I write this codes.
Thanks in advance.
private long analyzeAttachment(Metadata metadata, ContentHandler content, DataPipe data, long messageId) throws IOException, MessagingException{
long attid = IdGenerator.getUniqueID();
Logger.getLogger(ImapMailAnalyzer.class.getName()).log(Level.FINE, "Analyzed attachemnt {0} of message {1}", new Object[]{attid, messageId});
String attName = getAttachmentName(metadata);
data.writeRow(attid, "Abrakadabra", attName, messageId);
writeContent(attid, content, data);
return attid;
}
private String getAttachmentName(Metadata metadata){
if(metadata.get("resourceName") != null){
try {
return MimeUtility.decodeText(metadata.get("resourceName"));
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
return metadata.get("resourceName");
}
}
return "";
}

The following code uses jakarta.mail-api.
Usually you need to use multipart/xxx content type to send the email with attachments. In this case, you are dealing with javax.mail.internet.MimeMultipart.
So you can get all the body parts and check if they are attachments.
protected void processMimeMultipart(javax.mail.internet.MimeMultipart mimeMultipart) throws Exception {
for(int i = 0; i< mimeMultipart.getCount();i++){
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
int attachmentSize = getAttachmentSize(bodyPart);
}
}
protected int getAttachmentSize(final javax.mail.BodyPart bodyPart) throws Exception {
if(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
return bodyPart.getSize();
}
return -1;
}

Related

gRPC file upload detect content type of file on server

I am trying to do a file upload on via client streaming gRPC. Sending a file via streaming from client to server.
I have implemented this code for server side which receives the files. I would like the server to only accept the files of a specific type lets say image files of the format .png ,.bmp,.jpeg and many more may be.
So the client shouldn't be able to upload any other type of file other than the ones listed above.
How do I achieve this in gRPC ?
For the file upload sample I have referred this link
Server side code to process the request,
public class FileUploadService extends FileServiceGrpc.FileServiceImplBase {
private static final Path SERVER_BASE_PATH = Paths.get("src/test/resources/output");
#Override
public StreamObserver<FileUploadRequest> upload(StreamObserver<FileUploadResponse> responseObserver) {
return new StreamObserver<FileUploadRequest>() {
// upload context variables
OutputStream writer;
Status status = Status.IN_PROGRESS;
#Override
public void onNext(FileUploadRequest fileUploadRequest) {
try{
if(fileUploadRequest.hasMetadata()){
writer = getFilePath(fileUploadRequest);
}else{
writeFile(writer, fileUploadRequest.getFile().getContent());
}
}catch (IOException e){
this.onError(e);
}
}
#Override
public void onError(Throwable throwable) {
status = Status.FAILED;
this.onCompleted();
}
#Override
public void onCompleted() {
closeFile(writer);
status = Status.IN_PROGRESS.equals(status) ? Status.SUCCESS : status;
FileUploadResponse response = FileUploadResponse.newBuilder()
.setStatus(status)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
};
}
private OutputStream getFilePath(FileUploadRequest request) throws IOException {
var fileName = request.getMetadata().getName() + "." + request.getMetadata().getType();
return Files.newOutputStream(SERVER_BASE_PATH.resolve(fileName), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
private void writeFile(OutputStream writer, ByteString content) throws IOException {
writer.write(content.toByteArray());
writer.flush();
}
private void closeFile(OutputStream writer){
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Proto file
package file;
option java_package = "com.vinsguru.io";
option java_multiple_files = true;
message MetaData {
string name = 1;
string type = 2;
}
message File {
bytes content = 1;
}
enum Status {
PENDING = 0;
IN_PROGRESS = 1;
SUCCESS = 2;
FAILED = 3;
}
message FileUploadRequest {
oneof request {
MetaData metadata = 1;
File file = 2;
}
}
message FileUploadResponse {
string name = 1;
Status status = 2;
}
service FileService {
rpc upload(stream FileUploadRequest) returns(FileUploadResponse);
}
Assuming you don't want to just trust the file extension of the file, you will need to probe the file contents to determine its type. If you trust your client, you could consider just using FileTypeDetector.
If you don't trust your client, then your server must inspect the incoming file data and cancel the transfer if it detects an unsupported file type. To do this you could look at incorporating e.g. Apache Tika to your server.

Set Header order using javamail

I Want to set the header order of my mime message. I have tried implementing mimemessage and overridden writeTo method. But, im unable to understand how it works. I have sent a sample message but ended up receiving the headers two times. Can anyone please help me get clarity on this. Below is my Message class.
public class MyMessage extends MimeMessage{
private String subject;
private String encodingtype;
public MyMessage(Session session) {
super(session);
this.session=session;
}
#Override
public void writeTo(OutputStream out) throws java.io.IOException, MessagingException{
try{
String replyto = ("\""+displayname+"\" <"+displayfrom+">");
String fromheader = ("\""+displayname+"\" <"+mailfrom+">");
out.write(("Date: "+new Date()+"\r\n").getBytes("UTF-8"));
out.write(("From: "+fromheader+"\r\n").getBytes("UTF-8"));
out.write(("Reply-To: "+replyto+"\r\n").getBytes("UTF-8"));
out.write(("To: "+getAddress(email)+"\r\n").getBytes("UTF-8"));
out.write(("Content-Type: text/html; charset=\"UTF-8\"\r\n").getBytes("UTF-8"));
out.write(("Content-Transfer-Encoding: "+encodingtype+"\r\n").getBytes("UTF-8"));
out.write("\r\n".getBytes("UTF-8"));
out.write("<html><body><h1>HI</h1></body></html>\r\n".getBytes("UTF-8"));
}catch(Exception e){
System.out.println(e);
}
}
}
Thanks in advance.
Um, why do you need to control the header order?
By default, JavaMail will put the well-known headers in the order recommended by the internet RFCs. If you have some legitimate reason to put the headers in a different order, you can subclass MimeMessage and override the createInternetHeaders method to supply your own subclass of the InternetHeaders class that puts the headers in whatever order you want.
Or you can subclass MimeMessage and just override the writeTo method to fetch and output the headers in the order you want. You might find it helpful to look at the MimeMessage source code.
Finally I can able to set the header order. Thanks so much to Bill Shannon. Thanks for the help. Below is my message class.
public MyMessage(Session session, String fromdomain, String format,
String blastid, String listid, String offerid, int blastinstanceid,
String displayname, String displayfrom, String mailfrom, String email, String subject,
String encodingtype, String content) {
super(session);
this.session=session;
this.fromdomain = fromdomain;
this.format = format;
this.blastid = blastid;
this.listid = listid;
this.offerid = offerid;
this.blastinstanceid = blastinstanceid;
this.displayname = displayname;
this.displayfrom = displayfrom;
this.mailfrom = mailfrom;
this.email = email;
this.subject = subject;
this.content = content;
try{
setFrom(getAddress(displayfrom));
setSentDate(new Date());
setRecipients(RecipientType.TO, email);
setSubject(subject);
setReplyTo(getAddress2(mailfrom));
setHeader("Message-Id", getUniqueMessageIDValue(session,
fromdomain, format, blastid, listid, offerid, blastinstanceid));
}catch(Exception e){
System.out.println(e);
}
}
#Override
public void writeTo(OutputStream out, String[] ignoreList) throws
java.io.IOException, MessagingException{
LineOutputStream los = null;
try{
if (!saved)
saveChanges();
String replyto = ("\""+displayname+"\" <"+displayfrom+">");
String fromheader = ("\""+displayname+"\" <"+mailfrom+">");
los = new LineOutputStream(out);
los.writeln("Date: "+getHeader("Date", null));
los.writeln("Message-Id: " +getHeader("Message-Id",null).toString());
los.writeln("From: "+fromheader);
los.writeln("Reply-To: "+replyto);
los.writeln("To: "+getHeader("To",",").toString());
System.out.println("From header is "+getHeader("From",",")+" mail from is "+mailfrom);
//out.write(Message.RecipientType.TO, getAddress(email));
los.writeln("subject: "+getHeader("Subject",null).toString());
Enumeration hdrLines = getNonMatchingHeaderLines(ignoreList);
while (hdrLines.hasMoreElements())
los.writeln((String)hdrLines.nextElement());
los.writeln();
}catch(Exception e){
System.out.println(e);
}finally{
try{
if(los != null) los.flush();
}catch(Exception e){
System.out.println(e);
}
}
}

using dbpedia spotlight in java or scala

Does anyone know where to find a little how to on using dbpedia spotlight in java or scala? Or could anyone explain how it's done? I can't find any information on this...
The DBpedia Spotlight wiki pages would be a good place to start.
And I believe the installation page has listed the most popular ways (using a jar, or set up a web service) to use the application.
It includes instructions on using the Java/Scala API with your own installation, or calling the Web Service.
There are some additional data needed to be downloaded to run your own server for full service, good time to make a coffee for yourself.
you need download dbpedia spotlight (jar file) after that u can use next two classes ( author pablomendes ) i only make some change .
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org:80/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
private static String powered_by ="non";
private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT,
String powered_by,String spotter,String disambiguator,String showScores){
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
this.powered_by=powered_by;
this.spotter=spotter;
this.disambiguator=disambiguator;
this.showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
+ "&spotter=" + spotter
+ "&disambiguator=" + disambiguator
+ "&showScores=" + showScores
+ "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
LOG.error("JSON exception "+e);
}
}
return resources;
}
}
second class
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(HttpMethod method) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
LOG.error("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
LOG.error("Fatal transport error: " + e.getMessage());
LOG.error(method.getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
method.releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
main()
public static void main(String[] args) throws Exception {
String Question ="Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
System.out.println("resource : "+c.getResu());
}
I just add one little fix for your answer.
Your code is running, if you add the evaluate method call:
public static void main(String[] args) throws Exception {
String question = "Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
Lamine
In the request method of the second class (AnnotationClient) in Adel's answer, the author Pablo Mendes hasn't finished
TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
which is an annoying warning that needs to be removed by replacing
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
with
Reader in = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
StringWriter writer = new StringWriter();
org.apache.commons.io.IOUtils.copy(in, writer);
response = writer.toString();

Unit testing using MockMultipartHttpServletRequest (throws NullPointerException in ItemInputStream.makeAvailable)

I've written a transformer class that takes an HttpServletRequest and transforms it into another type that holds a pointer to the InputStream from the servlet request. (The idea is to abstract the incoming transport protocol from the request handling, so I could also write a similar transformer from FTP, for instance.)
Now I'm trying to write a unit test for this, and I'm having problems. I've managed to figure out the correct boilerplate to create a valid Multipart HTTP request (using the Spring classes MockMultipartHttpServletRequest and MockMultipartFile), but now I get a NullPointerException in the initialize() method of my UploadRequest class. I'm guessing the problem is that somehow the stream inside the MockMultipartHttpServletRequest isn't being initialized correctly, but I can't figure out what I should do differently.
Any suggestions would be gratefully accepted!
This is the stack trace:
java.lang.NullPointerException
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:976)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:886)
at java.io.InputStream.read(InputStream.java:82)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:96)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:66)
at org.apache.commons.fileupload.MultipartStream.readBodyData(MultipartStream.java:592)
at org.apache.commons.fileupload.MultipartStream.discardBodyData(MultipartStream.java:618)
at org.apache.commons.fileupload.MultipartStream.skipPreamble(MultipartStream.java:637)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:984)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:965)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.servlet.ServletFileUpload.getItemIterator(ServletFileUpload.java:148)
at com.ooyala.UploadRequest.initialize(UploadRequest.java:51)
at com.ooyala.UploadRequestTest.testCreateFromServletRequest(UploadRequestTest.java:57)
Here's an abbreviated version of my transformer class:
public class UploadRequest {
private Map<String, String> params;
private InputStream strIn;
private Logger Log = Logger.getLogger(UploadRequest.class.getName());
public UploadRequest()
{
params = new HashMap<String, String>();
}
public void initialize(HttpServletRequest sRequest,
ServletFileUpload upload)
throws IOException, FileUploadException
{
Enumeration<String> paramNames = sRequest.getParameterNames();
while (paramNames.hasMoreElements()) {
String pName = paramNames.nextElement();
params.put(pName, sRequest.getParameter(pName));
}
params.put("request_uri", sRequest.getRequestURI());
FileItemIterator iter = upload.getItemIterator(sRequest);
while (iter.hasNext()) {
FileItemStream item = iter.next();
try {
if (!item.isFormField()) {
// Skip form fields
params.put("original_file_name", item.getName());
strIn = item.openStream();
}
} catch (IOException ex) {
Log.severe("File uploading exception: " + ex.getMessage());
throw ex;
}
}
}
And here's the unit test:
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
// etc.... other imports
#RunWith(JMock.class)
public class UploadRequestTest {
private UploadRequest upRequest;
#Before
public void setUp()
{
context.setImposteriser(ClassImposteriser.INSTANCE);
upRequest = new UploadRequest();
}
#Test
public void testCreateFromServletRequest()
throws IOException, FileUploadException
{
String text_contents = "hello world";
MockMultipartHttpServletRequest sRequest =
new MockMultipartHttpServletRequest();
sRequest.setMethod("POST");
String boundary = generateBoundary();
String contentType = "multipart/form-data; boundary="+boundary;
sRequest.setContentType(contentType);
sRequest.setRequestURI("/foo");
sRequest.addParameter("test_param","test_value");
sRequest.addFile(
new MockMultipartFile("file1","test_upload.txt","text/plain",
text_contents.getBytes()));
ServletFileUpload upload = new ServletFileUpload();
assertTrue(upload.isMultipartContent(sRequest));
upRequest.initialize(sRequest, upload);
}
}
I have the same issue and I googled but no answer. I plugged in the source code from the library, You need to send content, whatever. The library might need to check if it is null in the skip method
MockMultipartHttpServletRequest request
request.setContent("whatever".getBytes());
Posted here for others
Add boundary condition
Generate contents as follows
MockMultipartHttpServletRequest request =
this.generateMockMultiPartHttpServletRequest(true);
MockMultipartFile mockMultipartFile = null;
try {
request.setContentType("multipart/form-data; boundary=-----1234");
request.setCharacterEncoding("text/plain");
String endline = "\r\n";
String bondary = "-----1234";
String textFile = this.encodeTextFile("-----1234", "\r\n", "file","test.csv",
"text/UTF-8", FileUtils.readFileToString((new File(csvFilePath)), "UTF-8"));
StringBuilder content = new StringBuilder(textFile.toString());
content.append(endline);
content.append(endline);
content.append(endline);
content.append("--");
content.append(bondary);
content.append("--");
content.append(endline);
request.setContent(content.toString().getBytes());
request.setMethod("POST");
mockMultipartFile = new MockMultipartFile("file",
FileUtils.readFileToByteArray(new File(csvFilePath)));
} catch (Exception e1) {
e1.printStackTrace();
}
request.addFile(mockMultipartFile);
Function to encode text
private String encodeTextFile(String bondary, String endline, String name,
String filename, String contentType, String content) {
final StringBuilder sb = new StringBuilder(64);
sb.append(endline);
sb.append("--");
sb.append(bondary);
sb.append(endline);
sb.append("Content-Disposition: form-data; name=\"");
sb.append(name);
sb.append("\"; filename=\"");
sb.append(filename);
sb.append("\"");
sb.append(endline);
sb.append("Content-Type: ");
sb.append(contentType);
sb.append(endline);
sb.append(endline);
sb.append(content);
return sb.toString();
}
I went through the same problem, after searching lot I got this post in which I answered with code that solved my problem.
The Shriprasad's solution works well for text file. But I had some problems with binary files.
https://stackoverflow.com/a/30541653/2762092

apache.commons.fileupload throws MalformedStreamException

I have got this piece of code (I didn't write, just maintaining):
public class MyMultipartResolver extends CommonsMultipartResolver{
public List parseEmptyRequest(HttpServletRequest request) throws IOException, FileUploadException {
String contentType = request.getHeader(CONTENT_TYPE);
int boundaryIndex = contentType.indexOf("boundary=");
InputStream input = request.getInputStream();
byte[] boundary = contentType.substring(boundaryIndex + 9).getBytes();
MultipartStream multi = new MultipartStream(input, boundary);
multi.setHeaderEncoding(getHeaderEncoding());
ArrayList items = new ArrayList();
boolean nextPart = multi.skipPreamble();
while (nextPart) {
Map headers = parseHeaders(multi.readHeaders());
// String fieldName = getFieldName(headers);
String subContentType = getHeader(headers, CONTENT_TYPE);
if (subContentType == null) {
FileItem item = createItem(headers, true);
OutputStream os = item.getOutputStream();
try {
multi.readBodyData(os);
} finally {
os.close();
}
items.add(item);
} else {
multi.discardBodyData();
}
nextPart = multi.readBoundary();
}
return items;
}
}
I am using commons-fileupload.jar version 1.2.1 and obviously the code is using some deprecated methods...
Anyway, while trying to use this code to upload a very large file (780 MB) I get this:
org.apache.commons.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:983)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:887)
at java.io.InputStream.read(InputStream.java:89)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:94)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:64)
at org.apache.commons.fileupload.MultipartStream.readBodyData(MultipartStream.java:593)
at org.apache.commons.fileupload.MultipartStream.discardBodyData(MultipartStream.java:619)
that is thrown from 'multi.discardBodyData();' line.
My question:
How can I avoid this error and be able to be able to succeed collecting the FileItems?
catch
(org.apache.commons.fileupload.MultipartStream.MalformedStreamException e)
{
e.printStackTrace();
return ERROR;
}
Catch the exception and handle it via ..either InputStream or Return Error use it in struts action tag

Categories

Resources