Browsers freeze by file download - java

I got a problem when files were download , I can't get any actions or events when clicking any links , butttons and menues after download process was done.
Below is my codes for excel file download button ...
Button btnDownloadExcel = new Button("Excel Download");
btnDownloadExcel.addStyleName("downloadButton");
btnDownloadExcel.addClickListener(new ClickListener() {
#Override
public void buttonClick(final ClickEvent event) {
StringBuilder url = new StringBuilder("/myproject/filedownload.html?category=excel");
url.append("&seq=" + 111);
getUI().getPage().open(url.toString(), "_self");
}
});
Below is servlet for handle excel file download request (I used JExcel API for excel file)
#WebServlet(value = "/filedownload.html")
public class DownloadServletController extends HttpServlet {
private final Logger log = LoggerFactory.getLogger(DownloadServletController.class);
protected final void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException, IOException {
String category = request.getParameter("category");
long seq = request.getParameter("seq") == null ? -1L : Long.parseLong(request.getParameter("seq"));
byte[] stream = null;
if (category.equals("excel")) {
try {
stream = getSampleExcelStream(seq);
}
catch (BusinessException e) {
log.error("Generating streams for " + category + " got Error !" + e);
}
ExcelSupport.createExcel("Test", seq, stream, response);
}
}
private byte[] getSampleExcelStream(final long seq) throws BusinessException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
String staticDir = System.getProperty("staticDir");
String templateDir = staticDir + "/templates/sample_excel_template.xls";
WorkbookSettings wsWrite = new WorkbookSettings();
wsWrite.setEncoding("UTF-8");
wsWrite.setAutoFilterDisabled(false);
WritableWorkbook workBook = Workbook.createWorkbook(baos, Workbook.getWorkbook(new File(templateDir)),
wsWrite);
workBook.write();
baos.close();
workBook.close();
}
catch (BiffException e) {
throw new BusinessException("Excel file Creating Error!");
}
catch (WriteException e) {
throw new BusinessException("Error ! writing excel file process has occured!");
}
catch (FileNotFoundException e) {
throw new BusinessException("FileNotFoundException, when getting stream for excel", e);
}
catch (IOException e) {
throw new BusinessException("IOException, when getting stream for excel", e);
}
return baos.toByteArray();
}
}
ExcelSupport.java is below
public final class ExcelSupport {
private ExcelSupport() {
}
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelSupport.class);
public static void createExcel(final String fileNamePrefix, final long seq,
final byte[] stream, final HttpServletResponse response) {
StringBuffer fileName = new StringBuffer();
fileName.append(fileNamePrefix + "_");
if (seq > -1) {
fileName.append("(uid-" + seq + ")_");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
fileName.append(sdf.format(new Date()));
fileName.append(".xls");
StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("inline");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(fileName);
response.setContentType("application/msexcel");
response.addHeader("Cache-Control", "max-age=30");
response.addHeader("Content-disposition", sbContentDispValue.toString());
response.setContentLength(stream.length);
try {
ServletOutputStream osStream = response.getOutputStream();
osStream.write(stream);
osStream.flush();
osStream.close();
}
catch (IOException e) {
LOGGER.error("Creating Excel for " + fileName + " got Error !" + e);
}
}
}
Can somebody correct me what I am wrong ? Download process was fine , nothing error and I got excel file successfully. But I have no idea why browser was freeze. I can't see any error logs or messages in IDE console and browser's console. Thanks for reading my question !
PS : I am sure this codes work fine and did not freeze on other GWT projects.

Now I found the problem . I used Network console of Firefox 31 and here is screen-shoot for before download and here is after download. I notice that I lost all web datas because the replacing url by getUI().getPage().open(url.toString(), "_self");
So , if I use others instead of _self , everythings were fine but browsers were block popups. I can't tell the users to enable popups of their browsers . So , finally I use Link component as below ..
Link linkDownloadExcel = new Link("Excel Download", new ExternalResource(
"/myproject/filedownload.html?category=excel&seq=" + 111), "_blank", -1, -1, BorderStyle.DEFAULT);
linkDownloadExcel.addStyleName("downloadButton");
linkDownloadExcel.setIcon(new ExternalResource("/myproject/images/excel-icon.png"));
hlButtonLayout.addComponent(linkDownloadExcel);

Related

Best practices to upload large files by chunks in Spring boot

I have A big file and i want to upload that in Server side. it's very important when occured any problem (like interrupting the internet or power cut ...) if i retry to upload, file uploaded from resume and doesn't need to send file from beginning.
I try this approach with sending file chunks but it seems that's not a good way, because a send chunks(byte arrays) directly in response Entity and this isn't good idea.
whatever if anybody can develop this approach and make this code a better code with better performance i appreciate that. does anybody known Best practice way to doing that??
and if u like my code, vote me
thanks :)
RestController
#RestController
#RequestMapping("/files")
public class Controller {
#Autowired
private MyService service;
#PutMapping("/upload/resume")
public Mono<ResponseEntity> uploadWithResume(#RequestPart("chunk")byte[] chunk,
#RequestPart("fileName")String fileName,
#RequestParam("length")Long length
) throws ParseException {
try {
return service.fileResumeUpload(chunk, fileName, length);
} catch (IOException e) {
e.printStackTrace();
return Mono.just(ResponseEntity.status(HttpStatus.PERMANENT_REDIRECT).build());
}
}
#RequestMapping(value = "/get/uploaded/size", method = RequestMethod.HEAD)
public Mono<ResponseEntity> getUploadedSize(#RequestParam("fileName") String fileName) throws IOException {
if (Files.exists(Paths.get("src/main/resources/" + fileName))) {
String size = String.valueOf(Files.size(Paths.get("src/main/resources/" + fileName)));
return Mono.just(ResponseEntity.ok()
.header("upload-offset", size)
.build());
} else{
return Mono.just(ResponseEntity.notFound()
.header("upload-offset" , "0").build());
}
}
}
Service
public Mono<ResponseEntity> fileResumeUpload(byte[] chunk , String fileName,long length) throws IOException, ParseException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("src/main/resources/" + fileName, true));
boolean uploaded = true;
try {
out.write(chunk);
} catch (IOException e) {
uploaded = false;
System.err.println("io exception");
} finally {
if (uploaded) {
out.close();
return Mono.just(ResponseEntity.ok()
.header("expiration-date", getExpirationDate())
.build());
} else {
out.close();
return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
}
}
}
Sending chunks with webTestClient
#Test
public void test1_upload_Expected_200StatusCode(){
try {
String fileName = "film.mkv";
RandomAccessFile raf = new RandomAccessFile(new File("src/test/resources/" + fileName), "rw");
long realSize = raf.length();
List<String> strings = webTestClient.head().uri("/files/get/uploaded/size?fileName=" + fileName)
.exchange().expectBody().returnResult().getResponseHeaders().get("upload-offset");
long uploadedSize = Long.valueOf(strings.get(0));
boolean f = false;
int sizeBuffer = 256 * 1024;
byte[] buffer = new byte[sizeBuffer];
MultiValueMap<String, Object> formData;
WebTestClient.ResponseSpec exchange = null;
System.out.println("first uploaded Size ; " + uploadedSize);
raf.seek(uploadedSize);
while (raf.read(buffer) != -1) {
formData = new LinkedMultiValueMap<>();
formData.add("fileName", fileName);
formData.add("chunk", buffer);
formData.add("length", realSize);
exchange = webTestClient.put().uri("/files/upload/resume")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(formData))
.exchange();
exchange.expectStatus().isOk();
if (exchange.expectBody().returnResult().getStatus().is5xxServerError()) {
return;
}
if (uploadedSize + 256 * 1024 > realSize) {
sizeBuffer = ((int) (realSize - uploadedSize));
System.out.println(sizeBuffer);
uploadedSize = uploadedSize + sizeBuffer;
System.out.println(uploadedSize);
buffer = new byte[sizeBuffer];
f=true;
} else uploadedSize = uploadedSize + sizeBuffer;
if (f) System.out.println(uploadedSize);
//System.out.println(uploadedSize);
float percent = ((float) uploadedSize / realSize * 100);
System.out.format("%.2f\n", percent);
}
if (exchange!=null)
exchange.expectStatus().isOk();
}
catch (Exception e){
e.printStackTrace();
System.err.println("channel closed!!!");
}
}

Post data into MYSql db using REST

I am very new to Vaadin, REST and Vertx. I want to post the data into MYSQL db from a JSON file. So I have created a base url "localhost:1443" and am able to call the handler in the other project where db is connected. But don't know to to pass the JSON file my current project to the another project where the MYSQL is configured.
Here am calling the method which is defined in REST,
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null; // Output stream to write to
file = new
File(VaadinService.getCurrent().getBaseDirectory().getAbsolutePath()
+"/Jsonfile/" + filename);
FILE_PATH =
VaadinService.getCurrent().getBaseDirectory().getAbsolutePath()
+"/Jsonfile/" + filename;
try{
fos = new FileOutputStream(file);
JSONArray products =
productsDataProvider.uploadCatalogs(file.toString());
Notification.show("Succesfully converted :)");
}
catch (final java.io.FileNotFoundException e) {
// Error while opening the file. Not reported here.
e.printStackTrace();
return null;
}
return fos; // Return the output stream to write to
}
this is where I defined method,
public JSONArray uploadCatalogs(String catalogClass) {
return dataProviderUtil.getResourceArray("gapi/upload_products", new
HashMap<String, String>(){
{
put("class", catalogClass);
}
});
This is the product handler in another project,
router.mountSubRouter("/gapi/upload_products", new
UploadCatalog(VertxInstance.get()));
Here the class defined,
public class UploadCatalog extends AbstractRouteHandler {
private final static Logger LOG =
LogManager.getLogger(UploadCatalog.class);
public UploadCatalog(Vertx vertx) {
super(vertx);
this.route().handler(BodyHandler.create());
this.get("/").handler(this::upload);
}
private void upload(RoutingContext routingContext) {
LOG.info("hello");
}
i can see the logger info in console...
I tried the below one,
private void upload(RoutingContext routingContext) {
JsonObject paramsObject = routingContext.getBodyAsJson();
JsonObject result = new JsonObject();
Integer id = LocalCache.getInstance().store(new
QueryData("product.insert", paramsObject));
LOG.info("Executing query:" + "product.insert" );
vertx.eventBus().send(DatabaseService.DB_QUERY, id,
(AsyncResult<Message<Integer>> res) -> {
QueryData resultData = (QueryData)
LocalCache.getInstance().remove(res.result().body());
if (resultData.errorFlag ||
resultData.updateResult.getUpdated() == 0) {
/*result.put("status", "error").put("error", "Error
in creating user profile.");
response.putHeader("content-type",
"application/json").end(result.encode());*/
} else {
/*LOG.info("Insert query (ms):" +
resultData.responseTimeInMillis);
this.sendNewUserProfile(data, response);*/
}
});
}
How to insert data in mysql db from JSON file?

JasperReports generated in a Servlet (GWT) does not appear

I am developing an application in GWT, I am using the api to generate JasperReports reports, initially tried to make the generation via RPC, which returned to the client a string with the path of the pdf created, but that did not work, now I'm trying to generate report by a normal servlet, but the report is generated, nothing appears on the screen, and no error is found in the browser console.
Details:
dev mode works perfectly.
on localhost: 8080 works perfectly.
The error is when the application is published in an external Tomcat
Here are my code
Servlet:
public class RelatorioPacienteServiceImpl extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletContext sc;
public void init(ServletConfig config) throws ServletException {
super.init(config);
sc = config.getServletContext();
}
#SuppressWarnings({ "unused", "unchecked", "rawtypes" })
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
Map m = req.getParameterMap();
Paciente paciente = new Paciente();
File reportFile = null;
String dir = sc.getRealPath(sc.getContextPath().replaceAll("\\\\", "/"));
Map parameters = new LinkedHashMap();
String path = dir + "/../reports/";// tomcat
path = path.replaceAll("\\\\", "/");
try {
paciente = PacienteDAO.getPacientePorId(Integer.parseInt(id));
List<Paciente> list = new ArrayList<>();
list.add(paciente);
HashMap parametros = new HashMap<String, Boolean>();
parametros.put("cpf", NumberMask.formatCpf(paciente.getCpf()));
parametros.put("telefone1",NumberMask.formatPhone(paciente.getTelefone1()));
parametros.put("telefone2",NumberMask.formatPhone(paciente.getTelefone2()));
parametros.put("telefoneResponsavel",NumberMask.formatPhone(paciente.getTelefoneResponsavel()));
parametros.put("dataNascimento",StringUtil.formatDate(paciente.getDataNascimento()));
switch (paciente.getEtnia()) {
case EtniaProps.BRANCA:
parametros.put("etnia","Branco");
break;
case EtniaProps.INDIGENA:
parametros.put("etnia","Indigena");
break;
case EtniaProps.PARDA:
parametros.put("etnia","Parda");
break;
case EtniaProps.PRETA:
parametros.put("etnia","Preta");
break;
default:
break;
}
reportFile = new File(path + "report_paciente.jasper");
byte[] bytes = null;
JRDataSource jrds = new JRBeanCollectionDataSource(list);
try {
bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parametros, jrds);
} catch (JRException ex) {
ex.printStackTrace();
System.out.println("Erro ao gerar o relatório " + ex.getMessage());
}
if (!list.isEmpty()) {
if (bytes != null && bytes.length > 0) {
resp.setContentType("application/pdf");
resp.setContentLength(bytes.length);
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write(bytes, 0, bytes.length);
outputStream.flush();
outputStream.close();
}
} else {
resp.setContentType("text/html");
ServletOutputStream outputStream = resp.getOutputStream();
String mensagem = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" charset=\"UTF-8\" content=\"text/html\">"
+ "<title>Incor lages</title>" + "</head>" + "<body>"
+ "<br><br><br><br><h1>Documento sem paginas" + "</body>" + "</html>";
outputStream.write(mensagem.getBytes(), 0, mensagem.getBytes().length);
resp.setContentLength(mensagem.getBytes().length);
outputStream.flush();
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Erro ao execura a query " + e.getMessage());
}
}
Calling servlet:
String url = GWT.getModuleBaseURL() + "relatorioPacienteService?id=" + paciente.getId();
Window.open(url, "_blank", "");
Any help would be appreciated
Can u print reportFile.getPath(). I doubt the path of .jasper file is incorrect.
First of all it would be even better If you can post your .jrxml file.
Based on the info available (report is generated, but blank), I think following is the area of concern:
paciente = PacienteDAO.getPacientePorId(Integer.parseInt(id));
List<Paciente> list = new ArrayList<>();
list.add(paciente);
Make sure PacienteDAO.getPacientePorId(Integer.parseInt(id)); is actually returning a bean. Beacuse If it does not return anything or returns null, the data source you use i.e. JRBeanCollectionDataSource, will have no data and hence nothing would be displayed.

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();

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