当前位置: 技术问答>java相关
高分求文件上传
来源: 互联网 发布时间:2015-07-28
本文导语: 做一个自己的上传类,将本地文件上传到tomcat服务器的指定路径下,如何定义服务器路径,最好来个原代码。 | import java.net.*; import java.io.*; import java.util.*; class FtpClient { static final b...
做一个自己的上传类,将本地文件上传到tomcat服务器的指定路径下,如何定义服务器路径,最好来个原代码。
|
import java.net.*;
import java.io.*;
import java.util.*;
class FtpClient {
static final boolean debug = false;
public static final int FTP_PORT = 21;
static int FTP_SUCCESS = 1;
static int FTP_TRY_AGAIN = 2;
static int FTP_ERROR = 3;
/** socket for data transfer */
private Socket dataSocket = null;
private boolean replyPending = false;
private boolean binaryMode = false;
private boolean passiveMode = false;
/** user name for login */
String user = null;
/** password for login */
String password = null;
/** last command issued */
String command;
/** The last reply code from the ftp daemon. */
int lastReplyCode;
/** Welcome message from the server, if any. */
public String welcomeMsg;
/** Array of strings (usually 1 entry) for the last reply
from the server. */
protected Vector serverResponse = new Vector(1);
/** Socket for communicating with server. */
protected Socket serverSocket = null;
/** Stream for printing to the server. */
public PrintWriter serverOutput;
/** Buffered stream for reading replies from server. */
public InputStream serverInput;
/** Return server connection status */
public boolean serverIsOpen() {
return serverSocket != null;
}
/**Set Passive mode Trasfers*/
public void setPassive(boolean mode) {
passiveMode = mode;
}
public int readServerResponse() throws IOException {
StringBuffer replyBuf = new StringBuffer(32);
int c;
int continuingCode = -1;
int code = -1;
String response;
if (debug) System.out.println("readServerResponse start");
try{
while (true) {
//if (debug) System.out.println("readServerResponse outer while loop: "+ serverInput.available());
while ((c = serverInput.read()) != -1) {
if (c == 'r') {
if ((c = serverInput.read()) != 'n')
replyBuf.append('r');
}
replyBuf.append((char)c);
if (c == 'n')
break;
}
if (debug) System.out.println("Now past inner while loop");
response = replyBuf.toString();
replyBuf.setLength(0);
if (debug) {
System.out.print(response);
}
try {
code = Integer.parseInt(response.substring(0, 3));
} catch (NumberFormatException e) {
code = -1;
} catch (StringIndexOutOfBoundsException e) {
/* this line doesn't contain a response code, so
we just completely ignore it */
continue;
}
serverResponse.addElement(response);
if (continuingCode != -1) {
/* we've seen a XXX- sequence */
if (code != continuingCode ||
(response.length() >= 4 && response.charAt(3) == '-')) {
continue;
} else {
/* seen the end of code sequence */
continuingCode = -1;
break;
}
} else if (response.length() >= 4 && response.charAt(3) == '-') {
continuingCode = code;
continue;
} else {
break;
}
}
}catch(Exception e){e.printStackTrace();}
if (debug) System.out.println("readServerResponse done");
return lastReplyCode = code;
}
/** Sends command cmd to the server. */
public void sendServer(String cmd) {
if (debug) System.out.println("sendServer start");
serverOutput.println(cmd);
if (debug) System.out.println("sendServer done");
}
/** Returns all server response strings. */
public String getResponseString() {
String s = new String();
for(int i = 0;i > 8) & 0xff) + ","
+ (portSocket.getLocalPort() & 0xff);
if (issueCommand(portCmd) == FTP_ERROR) {
e = new FtpProtocolException("PORT");
throw e;
}
if (issueCommand(cmd) == FTP_ERROR) {
e = new FtpProtocolException(cmd);
throw e;
}
dataSocket = portSocket.accept();
}
finally {
if(portSocket != null)
portSocket.close();
}
dataSocket = portSocket.accept();
portSocket.close();
}//end of port transfer
return dataSocket; // return the dataSocket
}
/** open a FTP connection to host host. */
public void openServer(String host) throws IOException, UnknownHostException {
int port = FTP_PORT;
if (serverSocket != null)
closeServer();
serverSocket = new Socket(host, FTP_PORT);
serverOutput = new PrintWriter(new BufferedOutputStream(serverSocket.getOutputStream()),true);
serverInput = new BufferedInputStream(serverSocket.getInputStream());
}
/** open a FTP connection to host host on port port. */
public void openServer(String host, int port) throws IOException, UnknownHostException {
if (serverSocket != null)
closeServer();
serverSocket = new Socket(host, port);
//serverSocket.setSoLinger(true,30000);
serverOutput = new PrintWriter(new BufferedOutputStream(serverSocket.getOutputStream()),
true);
serverInput = new BufferedInputStream(serverSocket.getInputStream());
if (readReply() == FTP_ERROR)
throw new FtpConnectException("Welcome message");
}
/**
* login user to a host with username user and password
* password
*/
public void login(String user, String password) throws IOException {
if (!serverIsOpen())
throw new FtpLoginException("Error: not connected to host.n");
this.user = user;
this.password = password;
if (issueCommand("USER " + user) == FTP_ERROR)
throw new FtpLoginException("Error: User not found.n");
if (password != null && issueCommand("PASS " + password) == FTP_ERROR)
throw new FtpLoginException("Error: Wrong Password.n");
}
import java.io.*;
import java.util.*;
class FtpClient {
static final boolean debug = false;
public static final int FTP_PORT = 21;
static int FTP_SUCCESS = 1;
static int FTP_TRY_AGAIN = 2;
static int FTP_ERROR = 3;
/** socket for data transfer */
private Socket dataSocket = null;
private boolean replyPending = false;
private boolean binaryMode = false;
private boolean passiveMode = false;
/** user name for login */
String user = null;
/** password for login */
String password = null;
/** last command issued */
String command;
/** The last reply code from the ftp daemon. */
int lastReplyCode;
/** Welcome message from the server, if any. */
public String welcomeMsg;
/** Array of strings (usually 1 entry) for the last reply
from the server. */
protected Vector serverResponse = new Vector(1);
/** Socket for communicating with server. */
protected Socket serverSocket = null;
/** Stream for printing to the server. */
public PrintWriter serverOutput;
/** Buffered stream for reading replies from server. */
public InputStream serverInput;
/** Return server connection status */
public boolean serverIsOpen() {
return serverSocket != null;
}
/**Set Passive mode Trasfers*/
public void setPassive(boolean mode) {
passiveMode = mode;
}
public int readServerResponse() throws IOException {
StringBuffer replyBuf = new StringBuffer(32);
int c;
int continuingCode = -1;
int code = -1;
String response;
if (debug) System.out.println("readServerResponse start");
try{
while (true) {
//if (debug) System.out.println("readServerResponse outer while loop: "+ serverInput.available());
while ((c = serverInput.read()) != -1) {
if (c == 'r') {
if ((c = serverInput.read()) != 'n')
replyBuf.append('r');
}
replyBuf.append((char)c);
if (c == 'n')
break;
}
if (debug) System.out.println("Now past inner while loop");
response = replyBuf.toString();
replyBuf.setLength(0);
if (debug) {
System.out.print(response);
}
try {
code = Integer.parseInt(response.substring(0, 3));
} catch (NumberFormatException e) {
code = -1;
} catch (StringIndexOutOfBoundsException e) {
/* this line doesn't contain a response code, so
we just completely ignore it */
continue;
}
serverResponse.addElement(response);
if (continuingCode != -1) {
/* we've seen a XXX- sequence */
if (code != continuingCode ||
(response.length() >= 4 && response.charAt(3) == '-')) {
continue;
} else {
/* seen the end of code sequence */
continuingCode = -1;
break;
}
} else if (response.length() >= 4 && response.charAt(3) == '-') {
continuingCode = code;
continue;
} else {
break;
}
}
}catch(Exception e){e.printStackTrace();}
if (debug) System.out.println("readServerResponse done");
return lastReplyCode = code;
}
/** Sends command cmd to the server. */
public void sendServer(String cmd) {
if (debug) System.out.println("sendServer start");
serverOutput.println(cmd);
if (debug) System.out.println("sendServer done");
}
/** Returns all server response strings. */
public String getResponseString() {
String s = new String();
for(int i = 0;i > 8) & 0xff) + ","
+ (portSocket.getLocalPort() & 0xff);
if (issueCommand(portCmd) == FTP_ERROR) {
e = new FtpProtocolException("PORT");
throw e;
}
if (issueCommand(cmd) == FTP_ERROR) {
e = new FtpProtocolException(cmd);
throw e;
}
dataSocket = portSocket.accept();
}
finally {
if(portSocket != null)
portSocket.close();
}
dataSocket = portSocket.accept();
portSocket.close();
}//end of port transfer
return dataSocket; // return the dataSocket
}
/** open a FTP connection to host host. */
public void openServer(String host) throws IOException, UnknownHostException {
int port = FTP_PORT;
if (serverSocket != null)
closeServer();
serverSocket = new Socket(host, FTP_PORT);
serverOutput = new PrintWriter(new BufferedOutputStream(serverSocket.getOutputStream()),true);
serverInput = new BufferedInputStream(serverSocket.getInputStream());
}
/** open a FTP connection to host host on port port. */
public void openServer(String host, int port) throws IOException, UnknownHostException {
if (serverSocket != null)
closeServer();
serverSocket = new Socket(host, port);
//serverSocket.setSoLinger(true,30000);
serverOutput = new PrintWriter(new BufferedOutputStream(serverSocket.getOutputStream()),
true);
serverInput = new BufferedInputStream(serverSocket.getInputStream());
if (readReply() == FTP_ERROR)
throw new FtpConnectException("Welcome message");
}
/**
* login user to a host with username user and password
* password
*/
public void login(String user, String password) throws IOException {
if (!serverIsOpen())
throw new FtpLoginException("Error: not connected to host.n");
this.user = user;
this.password = password;
if (issueCommand("USER " + user) == FTP_ERROR)
throw new FtpLoginException("Error: User not found.n");
if (password != null && issueCommand("PASS " + password) == FTP_ERROR)
throw new FtpLoginException("Error: Wrong Password.n");
}
|
/**
* login user to a host with username user and no password
* such as HP server which uses the form "/,user.
*/
public void login(String user) throws IOException {
if (!serverIsOpen())
throw new FtpLoginException("not connected to host");
this.user = user;
if (issueCommand("USER " + user) == FTP_ERROR)
throw new FtpLoginException("Error: Invalid Username.n");
}
/** GET a file from the FTP server in Ascii mode*/
public BufferedReader getAscii(String filename) throws IOException {
Socket s = null;
try {
s = openDataConnection("RETR " + filename);
} catch (FileNotFoundException fileException) {fileException.printStackTrace();}
return new BufferedReader( new InputStreamReader(s.getInputStream()));
}
/** GET a file from the FTP server in Binary mode*/
public BufferedInputStream getBinary(String filename) throws IOException {
Socket s = null;
try {
s = openDataConnection("RETR " + filename);
} catch (FileNotFoundException fileException) {fileException.printStackTrace();}
return new BufferedInputStream(s.getInputStream());
}
/** PUT a file to the FTP server in Ascii mode*/
public BufferedWriter putAscii(String filename) throws IOException {
Socket s = openDataConnection("STOR " + filename);
return new BufferedWriter(new OutputStreamWriter(s.getOutputStream()),4096);
}
/** PUT a file to the FTP server in Binary mode*/
public BufferedOutputStream putBinary(String filename) throws IOException {
Socket s = openDataConnection("STOR " + filename);
return new BufferedOutputStream(s.getOutputStream());
}
/** APPEND (with create) to a file to the FTP server in Ascii mode*/
public BufferedWriter appendAscii(String filename) throws IOException {
Socket s = openDataConnection("APPE " + filename);
return new BufferedWriter(new OutputStreamWriter(s.getOutputStream()),4096);
}
/** APPEND (with create) to a file to the FTP server in Binary mode*/
public BufferedOutputStream appendBinary(String filename) throws IOException {
Socket s = openDataConnection("APPE " + filename);
return new BufferedOutputStream(s.getOutputStream());
}
/** NLIST files on a remote FTP server */
public BufferedReader nlist() throws IOException {
Socket s = openDataConnection("NLST");
return new BufferedReader( new InputStreamReader(s.getInputStream()));
}
/** LIST files on a remote FTP server */
public BufferedReader list() throws IOException {
Socket s = openDataConnection("LIST");
return new BufferedReader( new InputStreamReader(s.getInputStream()));
}
/** CD to a specific directory on a remote FTP server */
public void cd(String remoteDirectory) throws IOException {
issueCommandCheck("CWD " + remoteDirectory);
}
/** Rename a file on the remote server */
public void rename(String oldFile, String newFile) throws IOException {
issueCommandCheck("RNFR " + oldFile);
issueCommandCheck("RNTO " + newFile);
}
/** Site Command */
public void site(String params) throws IOException {
issueCommandCheck("SITE "+ params);
}
/** Set transfer type to 'I' */
public void binary() throws IOException {
issueCommandCheck("TYPE I");
binaryMode = true;
}
/** Set transfer type to 'A' */
public void ascii() throws IOException {
issueCommandCheck("TYPE A");
binaryMode = false;
}
/** Send Abort command */
public void abort() throws IOException {
issueCommandCheck("ABOR");
}
/** Go up one directory on remots system */
public void cdup() throws IOException {
issueCommandCheck("CDUP");
}
/** Create a directory on the remote system */
public void mkdir(String s) throws IOException {
issueCommandCheck("MKD " + s);
}
/** Delete the specified directory from the ftp file system */
public void rmdir(String s) throws IOException {
issueCommandCheck("RMD " + s);
}
/** Delete the file s from the ftp file system */
public void delete(String s) throws IOException {
issueCommandCheck("DELE " + s);
}
/** Get the name of the present working directory on the ftp file system */
public void pwd() throws IOException {
issueCommandCheck("PWD");
}
/** Retrieve the system type from the remote server */
public void syst() throws IOException {
issueCommandCheck("SYST");
}
/** New FTP client connected to host host. */
public FtpClient(String host) throws IOException {
openServer(host, FTP_PORT);
}
/** New FTP client connected to host host, port port. */
public FtpClient(String host, int port) throws IOException {
openServer(host, port);
}
|
转贴
package com.upload;
import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletException;
public class upload{
private static String newline = "
";
private String uploadDirectory = ".";
private String ContentType = "";
private String CharacterEncoding = "";
private String getFileName(String s){
int i = s.lastIndexOf("");
if(i = s.length() - 1){
i = s.lastIndexOf("/");
if(i = s.length() - 1)
return s;
}
return s.substring(i + 1);
}
public void setUploadDirectory(String s){
uploadDirectory = s;
}
public void setContentType(String s){
ContentType = s;
int j;
if((j = ContentType.indexOf("boundary=")) != -1){
ContentType = ContentType.substring(j + 9);
ContentType = "--" + ContentType;
}
}
public void setCharacterEncoding(String s){
CharacterEncoding = s;
}
public void uploadFile( HttpServletRequest req) throws ServletException, IOException{
setCharacterEncoding(req.getCharacterEncoding());
setContentType(req.getContentType());
uploadFile(req.getInputStream());
}
public void uploadFile( ServletInputStream servletinputstream) throws ServletException, IOException{
String s5 = null;
String filename = null;
byte Linebyte[] = new byte[4096];
byte outLinebyte[] = new byte[4096];
int ai[] = new int[1];
int ai1[] = new int[1];
String line;
//得到文件名
while((line = readLine(Linebyte, ai, servletinputstream, CharacterEncoding)) != null){
int i = line.indexOf("filename=");
if(i >= 0){
line = line.substring(i + 10);
if((i = line.indexOf(""")) > 0)
line = line.substring(0, i);
break;
}
}
filename = line;
if(filename != null && !filename.equals(""")){
filename = getFileName(filename);
String sContentType = readLine(Linebyte, ai, servletinputstream, CharacterEncoding);
if(sContentType.indexOf("Content-Type") >= 0)
readLine(Linebyte, ai, servletinputstream, CharacterEncoding);
//File(String parent, String child)
//Creates a new File instance from a parent pathname string
//and a child pathname string.
File file = new File(uploadDirectory, filename);
//FileOutputStream(File file)
//Creates a file output stream to write to the file represented
//by the specified File object.
FileOutputStream fileoutputstream = new FileOutputStream(file);
while((sContentType = readLine(Linebyte, ai, servletinputstream, CharacterEncoding)) != null){
if(sContentType.indexOf(ContentType) == 0 && Linebyte[0] == 45)
break;
if(s5 != null){
//write(byte[] b, int off, int len)
//Writes len bytes from the specified byte array starting
//at offset off to this file output stream.
fileoutputstream.write(outLinebyte, 0, ai1[0]);
fileoutputstream.flush();
}
s5 = readLine(outLinebyte, ai1, servletinputstream, CharacterEncoding);
if(s5 == null // s5.indexOf(ContentType) == 0 && outLinebyte[0] == 45)
break;
fileoutputstream.write(Linebyte, 0, ai[0]);
fileoutputstream.flush();
}
byte byte0;
if(newline.length() == 1)
byte0 = 2;
else
byte0 = 1;
if(s5 != null && outLinebyte[0] != 45 && ai1[0] > newline.length() * byte0)
fileoutputstream.write(outLinebyte, 0, ai1[0] - newline.length() * byte0);
if(sContentType != null && Linebyte[0] != 45 && ai[0] > newline.length() * byte0)
fileoutputstream.write(Linebyte, 0, ai[0] - newline.length() * byte0);
fileoutputstream.close();
}
}
private String readLine(byte Linebyte[], int ai[],
ServletInputStream servletinputstream,
String CharacterEncoding){
try{
//readLine(byte[] buffer, int offset, int length)
//Reads a line from the POST data.
ai[0] = servletinputstream.readLine(Linebyte, 0, Linebyte.length);
if(ai[0] == -1)
return null;
}catch(IOException _ex){
return null;
}
try{
if(CharacterEncoding == null){
//用缺省的编码方式把给定的byte数组转换为字符串
//String(byte[] bytes, int offset, int length)
return new String(Linebyte, 0, ai[0]);
}else{
//用给定的编码方式把给定的byte数组转换为字符串
//String(byte[] bytes, int offset, int length, String enc)
return new String(Linebyte, 0, ai[0], CharacterEncoding);
}
}catch(Exception _ex){
return null;
}
}
/*
public int readLine(byte[] buffer,
int offset,
int length) throws java.io.IOException
从POST来的数据中读一行
参数:
buffer - buffer to hold the line data
offset - offset into the buffer to start
length - maximum number of bytes to read.
Returns:
number of bytes read or -1 on the end of line.
*/
}
package com.upload;
import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletException;
public class upload{
private static String newline = "
";
private String uploadDirectory = ".";
private String ContentType = "";
private String CharacterEncoding = "";
private String getFileName(String s){
int i = s.lastIndexOf("");
if(i = s.length() - 1){
i = s.lastIndexOf("/");
if(i = s.length() - 1)
return s;
}
return s.substring(i + 1);
}
public void setUploadDirectory(String s){
uploadDirectory = s;
}
public void setContentType(String s){
ContentType = s;
int j;
if((j = ContentType.indexOf("boundary=")) != -1){
ContentType = ContentType.substring(j + 9);
ContentType = "--" + ContentType;
}
}
public void setCharacterEncoding(String s){
CharacterEncoding = s;
}
public void uploadFile( HttpServletRequest req) throws ServletException, IOException{
setCharacterEncoding(req.getCharacterEncoding());
setContentType(req.getContentType());
uploadFile(req.getInputStream());
}
public void uploadFile( ServletInputStream servletinputstream) throws ServletException, IOException{
String s5 = null;
String filename = null;
byte Linebyte[] = new byte[4096];
byte outLinebyte[] = new byte[4096];
int ai[] = new int[1];
int ai1[] = new int[1];
String line;
//得到文件名
while((line = readLine(Linebyte, ai, servletinputstream, CharacterEncoding)) != null){
int i = line.indexOf("filename=");
if(i >= 0){
line = line.substring(i + 10);
if((i = line.indexOf(""")) > 0)
line = line.substring(0, i);
break;
}
}
filename = line;
if(filename != null && !filename.equals(""")){
filename = getFileName(filename);
String sContentType = readLine(Linebyte, ai, servletinputstream, CharacterEncoding);
if(sContentType.indexOf("Content-Type") >= 0)
readLine(Linebyte, ai, servletinputstream, CharacterEncoding);
//File(String parent, String child)
//Creates a new File instance from a parent pathname string
//and a child pathname string.
File file = new File(uploadDirectory, filename);
//FileOutputStream(File file)
//Creates a file output stream to write to the file represented
//by the specified File object.
FileOutputStream fileoutputstream = new FileOutputStream(file);
while((sContentType = readLine(Linebyte, ai, servletinputstream, CharacterEncoding)) != null){
if(sContentType.indexOf(ContentType) == 0 && Linebyte[0] == 45)
break;
if(s5 != null){
//write(byte[] b, int off, int len)
//Writes len bytes from the specified byte array starting
//at offset off to this file output stream.
fileoutputstream.write(outLinebyte, 0, ai1[0]);
fileoutputstream.flush();
}
s5 = readLine(outLinebyte, ai1, servletinputstream, CharacterEncoding);
if(s5 == null // s5.indexOf(ContentType) == 0 && outLinebyte[0] == 45)
break;
fileoutputstream.write(Linebyte, 0, ai[0]);
fileoutputstream.flush();
}
byte byte0;
if(newline.length() == 1)
byte0 = 2;
else
byte0 = 1;
if(s5 != null && outLinebyte[0] != 45 && ai1[0] > newline.length() * byte0)
fileoutputstream.write(outLinebyte, 0, ai1[0] - newline.length() * byte0);
if(sContentType != null && Linebyte[0] != 45 && ai[0] > newline.length() * byte0)
fileoutputstream.write(Linebyte, 0, ai[0] - newline.length() * byte0);
fileoutputstream.close();
}
}
private String readLine(byte Linebyte[], int ai[],
ServletInputStream servletinputstream,
String CharacterEncoding){
try{
//readLine(byte[] buffer, int offset, int length)
//Reads a line from the POST data.
ai[0] = servletinputstream.readLine(Linebyte, 0, Linebyte.length);
if(ai[0] == -1)
return null;
}catch(IOException _ex){
return null;
}
try{
if(CharacterEncoding == null){
//用缺省的编码方式把给定的byte数组转换为字符串
//String(byte[] bytes, int offset, int length)
return new String(Linebyte, 0, ai[0]);
}else{
//用给定的编码方式把给定的byte数组转换为字符串
//String(byte[] bytes, int offset, int length, String enc)
return new String(Linebyte, 0, ai[0], CharacterEncoding);
}
}catch(Exception _ex){
return null;
}
}
/*
public int readLine(byte[] buffer,
int offset,
int length) throws java.io.IOException
从POST来的数据中读一行
参数:
buffer - buffer to hold the line data
offset - offset into the buffer to start
length - maximum number of bytes to read.
Returns:
number of bytes read or -1 on the end of line.
*/
}
|
package java6;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.jspsmart.upload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=Shift_JIS";
//Initialize global variables
private ServletConfig config; /** * Init the servlet */
final public void init(ServletConfig config) throws ServletException {
this.config = config;
}
final public ServletConfig getServletConfig() {
return config;
}
public void init() throws ServletException {
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
SmartUpload mySmartUpload = new SmartUpload();
String fathername=null;
try {
// Initialization
mySmartUpload.initialize(config,request,response);
// Upload
mySmartUpload.setDenyPhysicalPath(false);
mySmartUpload.upload();
fathername=mySmartUpload.getRequest().getParameter("fathername");
// Save the file with the original name
// in a virtual path of the web server
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
String truename=myFile.getFileName();
java.io.File file=new java.io.File(fathername,truename);
if(file.exists())
{
out.println(truename+"というフアイルがもうありました");
}
else{
mySmartUpload.save(fathername,mySmartUpload.SAVE_PHYSICAL);
//response.sendRedirect("sharefile.jsp?fathername="+fathername);
out.println("upload成功しました。");
out.println("
あなたは"+truename+"というファイルを作成しました");
// Display the result
}
} catch (Exception e){
out.println("Unable to upload the file.
");
out.println("Error : " + e.toString());
}
}
//Clean up resources
public void destroy() {
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.jspsmart.upload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=Shift_JIS";
//Initialize global variables
private ServletConfig config; /** * Init the servlet */
final public void init(ServletConfig config) throws ServletException {
this.config = config;
}
final public ServletConfig getServletConfig() {
return config;
}
public void init() throws ServletException {
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
SmartUpload mySmartUpload = new SmartUpload();
String fathername=null;
try {
// Initialization
mySmartUpload.initialize(config,request,response);
// Upload
mySmartUpload.setDenyPhysicalPath(false);
mySmartUpload.upload();
fathername=mySmartUpload.getRequest().getParameter("fathername");
// Save the file with the original name
// in a virtual path of the web server
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
String truename=myFile.getFileName();
java.io.File file=new java.io.File(fathername,truename);
if(file.exists())
{
out.println(truename+"というフアイルがもうありました");
}
else{
mySmartUpload.save(fathername,mySmartUpload.SAVE_PHYSICAL);
//response.sendRedirect("sharefile.jsp?fathername="+fathername);
out.println("upload成功しました。");
out.println("
あなたは"+truename+"というファイルを作成しました");
// Display the result
}
} catch (Exception e){
out.println("Unable to upload the file.
");
out.println("Error : " + e.toString());
}
}
//Clean up resources
public void destroy() {
}
}