大家好,我找到了将数据库上传到localhost的方法。 这是我的Serverlet
@WebServlet("/UploadDownloadFileServlet")
public class UploadDownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
@Override
public void init() throws ServletException {
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute(
"FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
if (fileName == null || fileName.equals("")) {
throw new ServletException("File Name can't be null or empty");
}
File file = new File(request.getServletContext().getAttribute(
"FILES_DIR")
+ File.separator + fileName);
if (!file.exists()) {
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::" + file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file);
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = response.getOutputStream();
byte[] bufferData = new byte[1024];
int read = 0;
while ((read = fis.read(bufferData)) != -1) {
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
System.out.println("File downloaded at client successfully");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
throw new ServletException(
"Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while (fileItemsIterator.hasNext()) {
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName=" + fileItem.getFieldName());
System.out.println("FileName=" + fileItem.getName());
System.out.println("ContentType=" + fileItem.getContentType());
System.out.println("Size in bytes=" + fileItem.getSize());
File file = new File(request.getServletContext().getAttribute(
"FILES_DIR")
+ File.separator + fileItem.getName());
System.out.println("Absolute Path at server="
+ file.getAbsolutePath());
fileItem.write(file);
}
}
是的,我接下来是android的代码:
class DatabaseAction extends AsyncTask<Void, Integer, Void> {
SQLiteDatabase db;
// String link =
// "http://192.168.56.101:8080/UploadServlet301/upload.jsp";
String link = "http://192.168.56.101:8080/ServletFileUploadDownloadExample/";
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
URL url;
String folderPath;
String arrayOfFiles[];
File root;
File allFiles;
String urlServer = "http://urluploadscriptaddress.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
public DatabaseAction(SQLiteDatabase db) {
this.db = db;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Logger.error("start");
}
@Override
protected Void doInBackground(Void... params) {
Logger.error("path: " + db.getPath());
uploadFile(db.getPath());
return null;
}
public long uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
long TotalSize = 0;
HttpURLConnection comm = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10240;
File sourceFile = new File(sourceFileUri);
int serverResonseCode;
if (!sourceFile.isFile()) {
Log.e("UploadFile", "Source File not Exist: " + sourceFile);
return 0;
} else {
try {
FileInputStream fis = new FileInputStream(db.getPath());
URL url = new URL(link);
comm = (HttpURLConnection) url.openConnection();
comm.setDoInput(true);
comm.setDoOutput(true);
comm.setUseCaches(false);
comm.setRequestMethod("POST");
comm.setRequestProperty("Connection", "Keep-Alive");
comm.setRequestProperty("ENCTYPE", "multipart/form-data");
comm.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
comm.setRequestProperty("fileName", fileName);
dos = new DataOutputStream(comm.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"fileName\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fis.available();
TotalSize = bytesAvailable;
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
publishProgress(bytesRead);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResonseCode = comm.getResponseCode();
if (serverResonseCode == 200) {
Logger.error("File Upload Completed.");
}
fis.close();
dos.flush();
dos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e("Upload file to server", "error: " + e.getMessage(),e);
} catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server", "error: " + e.getMessage(),e);
}
return TotalSize;
}
}
现在我从网站上传,它返回服务器中文件的位置:
字段名=文件名
文件名= EPL-v10.html
的ContentType = text / html的
以字节为单位的大小= 16536
服务器上的绝对路径= C:\ Users \ dungdv4 \ Desktop \ Android我的代码 Stack \ sv tomcat \ tmpfiles \ epl-v10.html
但在日食运行中,它说:
03-04 08:27:48.249:E / ###########(2643):开始
03-04 08:27:48.249:E / ###########(2643):路径: /数据/数据/ COM ########### ########### /数据库/ ########### - 。分贝
03-04 08:27:48.253:E / ###########(2643):文件上传已完成。
03-04 08:27:48.253:E / ###########(2643):在此处查看上传的文件: 的/ var / WWW /上传
03-04 08:27:48.261:E / ###########(2643):结果:null
它表示文件上传成功,但我无法在服务器中找到此文件
答案 0 :(得分:0)
我找到了解决方案,似乎我被贬低了:)
让我们看看
在servlet中 @WebServlet("/UploadDownloadFileServlet")
。
所以我需要将链接更改为String link = "192.168.56.101:8080/ServletFileUploadDownloadExample/UploadDownloadFileServlet";
好了现在它就像魅力一样,谢谢大家