[英]Handling file upload in a non-blocking manner
后台主題就在這里
只是為了明確目標 - 用戶將上傳一個大文件,並且必須立即重定向到另一個頁面以進行不同的操作。 但是文件很大,需要時間從控制器的InputStream中讀取。 所以我不情願地決定派一個新線程來處理這個I / O. 代碼如下:
控制器servlet
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("In Controller.doPost(...)");
TempModel tempModel = new TempModel();
tempModel.uploadSegYFile(request, response);
System.out.println("Forwarding to Accepted.jsp");
/*try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
request.getRequestDispatcher("/jsp/Accepted.jsp").forward(request,
response);
}
模型類
package com.model;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.utils.ProcessUtils;
public class TempModel {
public void uploadSegYFile(HttpServletRequest request,
HttpServletResponse response) {
// TODO Auto-generated method stub
System.out.println("In TempModel.uploadSegYFile(...)");
/*
* Trigger the upload/processing code in a thread, return immediately
* and notify when the thread completes
*/
try {
FileUploaderRunnable fileUploadRunnable = new FileUploaderRunnable(
request.getInputStream());
/*
* Future<FileUploaderRunnable> future = ProcessUtils.submitTask(
* fileUploadRunnable, fileUploadRunnable);
*
* FileUploaderRunnable processed = future.get();
*
* System.out.println("Is file uploaded : " +
* processed.isFileUploaded());
*/
Thread uploadThread = new Thread(fileUploadRunnable);
uploadThread.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*
* catch (InterruptedException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } catch (ExecutionException e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
System.out.println("Returning from TempModel.uploadSegYFile(...)");
}
}
The Runnable
package com.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class FileUploaderRunnable implements Runnable {
private boolean isFileUploaded = false;
private InputStream inputStream = null;
public FileUploaderRunnable(InputStream inputStream) {
// TODO Auto-generated constructor stub
this.inputStream = inputStream;
}
public void run() {
// TODO Auto-generated method stub
/* Read from InputStream. If success, set isFileUploaded = true */
System.out.println("Starting upload in a thread");
File outputFile = new File("D:/06c01_output.seg");/*
* This will be changed
* later
*/
FileOutputStream fos;
ReadableByteChannel readable = Channels.newChannel(inputStream);
ByteBuffer buffer = ByteBuffer.allocate(1000000);
try {
fos = new FileOutputStream(outputFile);
while (readable.read(buffer) != -1) {
fos.write(buffer.array());
buffer.clear();
}
fos.flush();
fos.close();
readable.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File upload thread completed");
}
public boolean isFileUploaded() {
return isFileUploaded;
}
}
我的疑問/疑惑:
當前代碼給出了一個非常明顯的異常 - 因為doPost(...)方法在run()方法完成之前返回,所以流是不可訪問的 :
In Controller.doPost(...) In TempModel.uploadSegYFile(...) Returning from TempModel.uploadSegYFile(...) Forwarding to Accepted.jsp Starting upload in a thread Exception in thread "Thread-4" java.lang.NullPointerException at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:512) at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:497) at org.apache.coyote.http11.InternalInputBuffer$InputStreamInputBuffer.doRead(InternalInputBuffer.java:559) at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:324) at org.apache.coyote.Request.doRead(Request.java:422) at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:287) at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:407) at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:310) at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:202) at java.nio.channels.Channels$ReadableByteChannelImpl.read(Unknown Source) at com.model.FileUploaderRunnable.run(FileUploaderRunnable.java:39) at java.lang.Thread.run(Unknown Source)
請記住第1點,Executor框架的使用是否對我有幫助?
package com.utils; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; public final class ProcessUtils { /* Ensure that no more than 2 uploads,processing req. are allowed */ private static final ScheduledThreadPoolExecutor threadPoolExec = new ScheduledThreadPoolExecutor( 2); public static <T> Future<T> submitTask(Runnable task, T result) { return threadPoolExec.submit(task, result); } }
那么我應該如何確保用戶不會阻止並且流仍然可訪問,以便可以從中讀取(上載的)文件 ?
實際上它沒有。你正在嘗試生成線程並讀取POST請求的內容,並且你也試圖將用戶轉發到具有相同請求對象的另一個頁面。 這會混淆servlet容器。
你可以
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.