This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Servlets and the fly likes Help me Plz.........Confused: Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Help me Plz.........Confused:" Watch "Help me Plz.........Confused:" New topic
Author

Help me Plz.........Confused:

Bikash Paul
Ranch Hand

Joined: Dec 04, 2001
Posts: 342
Hi all friends,
I am facing problem with my uploading of file programme.In my client side interface I want to give facility to client that they can "Pause" the uploading of one file in between just like cancelling it and can start uploading of new file from scratch and when they want to restart("Resume") that file again which they paused it in between it should be start from that point where they paused it means if they paused it at 40% it should start from 41% not from scratch.For monitoring upload iam using progress monitor dialog .Now for that :-
1.client have to send query to remote server to get the length of remote file which is incomplete.
2. client to skip ahead in the file reading up to the length reported by the servlet.
3.And should send those portion of file to server which is incomplete and server will have to APPEND the data to the file,rather than writing it.
4.Or client can simply begin a new upload from scratch.
5.the servlet would have to be able to distinguish these two cases 3 and 4.
I couldn't decide(confused)how I can start to give this facility to client.My programme working fine with simple uploading without those options.Can any one guide me how I can do that or give me some code for that.I tried it as per my below codes but couldn't slove my problem.

Client programme:-
-----------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class SendFileToServletPM
extends JFrame
implements ActionListener, Observer
{
private JTextArea logarea;
private JPanel content;
private JTextField filename;
private JTextField destdir;
private JTextField servlet;
private JButton send;
private JButton pause, resume;
private ProgressMonitoredDataTransfer xfer;

public static final String SERVLET_DEF =
"http://127.0.0.1:8080/examples/servlet/RecvFileServlet";
public SendFileToServletPM() {
super("Send File To Servlet Test");
xfer = null;
content = new JPanel(new BorderLayout());
JPanel top = new JPanel(new BorderLayout(5,5));
JPanel filepanel = new JPanel(new BorderLayout(3,3));
JPanel urlpanel = new JPanel(new BorderLayout(3,3));
JPanel destpanel = new JPanel(new BorderLayout(3,3));
JPanel inputpanel = new JPanel(new GridLayout(3,1));
filename = new JTextField(40);
servlet = new JTextField(40);
destdir = new JTextField(40);
servlet.setText(SERVLET_DEF);
destdir.setText(".");
JPanel btnPanel;
btnPanel = new JPanel(new GridLayout(3,1));
send = new JButton("Send");
pause = new JButton("Pause");
resume = new JButton("Resume");
btnPanel.add(send);
btnPanel.add(pause);
btnPanel.add(resume);
filepanel.add(new JLabel("Send file:"), BorderLayout.WEST);
filepanel.add(filename, BorderLayout.CENTER);
destpanel.add(new JLabel("Dest dir:"), BorderLayout.WEST);
destpanel.add(destdir, BorderLayout.CENTER);
urlpanel.add(new JLabel("To servlet:"), BorderLayout.WEST);
urlpanel.add(servlet, BorderLayout.CENTER);
inputpanel.add(filepanel);
inputpanel.add(destpanel);
inputpanel.add(urlpanel);
top.add(inputpanel, BorderLayout.CENTER);
top.add(btnPanel, BorderLayout.EAST);
content.add(top, BorderLayout.NORTH);
logarea = new JTextArea(10,44);
content.add(new JScrollPane(logarea), BorderLayout.CENTER);
setContentPane(content);
send.addActionListener(this);
pause.addActionListener(this);
resume.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(1);
} });
pack();
show();
}
class Loglater implements Runnable {
String msg;
public Loglater(String s) { msg = s; };
public void run() { log(msg); }
}
public void log(String msg) {
if (SwingUtilities.isEventDispatchThread()) {
logarea.append(msg);
logarea.append("\n");
System.err.println(msg);
}
else {
SwingUtilities.invokeLater(new Loglater(msg));
}
return;
}
URL u1;
URLConnection uc;
public String doSendToServletPart1(String base, String path, File f) {
// now do the file and networking stuff...
try {
// step 0 - open file URL
log("step 0 - open file URL");
FileInputStream fis = new FileInputStream(f);
// step 1 - create URL
log("step 1 - create URL");
// u1 = new URL(base + "/" + f.getName());
u1 = new URL(base + "?name=" +
URLEncoder.encode(f.getName()) +
"&path=" +
URLEncoder.encode(path));
// step 2 - open URLConnection
log("step 2 - open URLConnection");
uc = u1.openConnection();
// step 3 - set settings on URLConnection
log("step 3 - set settings on URLConnection");
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
uc.setRequestProperty("Content-Type","application/octet-stream");
uc.setRequestProperty("Content-Length", "" + f.length());
((HttpURLConnection)uc).setRequestMethod("POST");
// step 4 - get output stream
log("step 4 - get output stream");
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
// step 5 - perform the copy
dos.writeLong(f.length());
xfer = new ProgressMonitoredDataTransfer(this,
fis, dos,
(int)(f.length()),
"Sending " + f.getName(),
true);
xfer.addObserver(this);
return "Transfer Part 1 succeeded, transfer started.";
}
catch (Exception e) {
log("Problem: " + e);
return "Transfer Part 1 apparently failed.";
}
}
public String doSendToServletPart2() {
try {
// step 7 - open the input stream
log("step 7 - open the input stream");
InputStream is = uc.getInputStream();
// step 8 - read the input stream
int cc;
byte [] buf = new byte[512];
log("step 8 - read the input stream");
for(cc = is.read(buf, 0, 512); cc > 0; cc = is.read(buf, 0, 512)) {
log(new String(buf, 0, cc));
}
// step 9 - close the input stream
log("step 9 - close the input stream");
is.close();
// report the good news!
return "Transfer Part 2 apparently succeeded!";
}
catch (Exception e) {
log("Problem: " + e);
return "Transfer apparently failed.";
}
finally {
uc = null;
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == send) {
String base;
String fn;
base = servlet.getText();
fn = filename.getText();
if (fn.length() < 1) {
log("File name too short.");
return;
}
if (base.length() < 7) {
log("Servlet base URL too short.");
return;
}
if (uc != null) {
log("Transfer in progress, please wait.");
return;
}
File f = new File(fn);
String path = destdir.getText();
String result;
result = doSendToServletPart1(base, path, f);
log(result);
}
else if (e.getSource() == pause) {
if (xfer == null) {
log("No transfer in progress, cannot pause.");
return;
}
if (xfer.isPaused()) {
log("Transfer is already paused!");
return;
}
xfer.setPaused(true);
log("** Transfer paused.");
}
else if (e.getSource() == resume) {
if (xfer == null) {
log("No transfer in progress, cannot resume.");
return;
}
if (!xfer.isPaused()) {
log("Transfer is not paused, cannot resume!");
return;
}
xfer.setPaused(false);
log("** Transfer resumed.");
}
}
public void update(Observable obs, Object arg) {
if (obs instanceof ProgressMonitoredDataTransfer &&
arg != null &&
uc != null)
{
doSendToServletPart2();
}
}

public static void main(String args[]) {
SendFileToServletPM sspm;
sspm = new SendFileToServletPM();
}
Servlet programme:-
-----------------
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
public class RecvFileServlet extends HttpServlet {
public static final String BASE_DIR = "d:\\temp";
File baseFile;
public void init() throws ServletException {
super.init();
baseFile = new File(BASE_DIR);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.sendError(response.SC_NOT_ACCEPTABLE, "Must use POST method.");
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Note that the code below is not secure, and is
// subject to abuse by a malicious client!
String filename;
filename = request.getParameter("name");
String path;
path = request.getParameter("path");
File outfile = new File(filename);
System.out.println("path value = " + ((path == null)?("null") path)));
System.out.println("name value = " + ((filename == null)?("null") filename)));
if (path != null && filename != null) {
String pathlocal = path.replace('/', File.separatorChar);
// ensure it is a relative path
if (pathlocal.startsWith(File.separator))
pathlocal = pathlocal.substring(1);
File pfile = new File(baseFile, pathlocal);
pfile.mkdirs();
outfile = new File(pfile, filename);
System.err.println("Final output file: " +
outfile.getAbsolutePath());
}
// create a DataInputStream to read from sender
DataInputStream dis;
dis = new DataInputStream(request.getInputStream());
OutputStream os;
// create file output stream to write the output file
System.err.println("Using output file " + outfile);
os = new BufferedOutputStream(new FileOutputStream(outfile));
int cc;
byte [] buf = new byte[512];
long lim, tot = 0;
// read the number of bytes we should expect
lim = dis.readLong();
// read from the input stream and write to the file
try {
System.err.println("Reading " + lim + " bytes...");
for(cc = dis.read(buf, 0, 512);
cc > 0 && tot < lim;
cc = dis.read(buf, 0, 512))
{
os.write(buf, 0, cc);
tot += cc;
System.err.print("+" + cc + "(" + tot + ")");
if (tot >= lim) break;
}
}
catch (IOException ie) {
try { os.close(); } catch (Exception e2) { }
System.err.println("Exception during file transfer!");
}
// done reading and writing, close the file output stream
System.err.println("Read " + tot + " bytes.");
os.close();
// Send back a response message to the application
response.setContentType("text/plain");
PrintStream pos = new PrintStream(response.getOutputStream());
pos.println("Received " + tot + " bytes.");
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help me Plz.........Confused: