相關閱讀:Android 拍照上傳代碼示例 https://www.linuxidc.com/Linux/2011-11/47617.htm
下面是一個用於接收拍照上傳文件的 Servlet 服務端程序 UploadFileServlet.java:
package com.hemi.rhet.servlet;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
public class UploadFileServlet extends HttpServlet
{
private static Logger log = Logger.getLogger(UploadFileServlet.class);
private static final String OBLIQUE_LINE = "/";
private static final String OPPOSITE_OBLIQUE_LINE = "////";
private static final String WEBPOSITION = "webapps";
private static final String SBPATH = "UploadedFiles/";
File outdir = null;
File outfile = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
byte[] bs = new byte[1024];
String uploadFName = null;
String orderNo = null;
String userId = null;
String attachType = "2";
public void init() throws ServletException
{
}
public void doGet(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException
{
String root = this.getServletContext().getRealPath("/");
root = root.replaceAll("////", "/");
try
{
StringBuffer destFName = new StringBuffer();
destFName.append(getRealDir(root)).append(SBPATH);
outdir = new File(destFName.toString());
request.setCharacterEncoding("UTF-8");
uploadFName = request.getParameter("filename");
uploadFName = request.getHeader("filename");
if (isEmpty(uploadFName)) uploadFName = "filename.jpg";
String desc = request.getParameter("desc");
if (desc==null) desc = "";
if (true)
{
destFName.append(getDatedFName(uploadFName));
outfile = new File(destFName.toString());
bis = new BufferedInputStream(request.getInputStream());
uploadFile();
response.setHeader("resultcode", "0");
}
else if (desc.length() > 400/2) {
response.setHeader("resultcode", "3");
}
else
{
if (log.isDebugEnabled())
{
log.debug("調用格式錯誤!");
}
response.sendError(100, "參數錯誤!");
response.setHeader("resultcode", "1");
}
} catch (SQLException e) {
if (log.isDebugEnabled()) {
log.debug(e);
}
response.setHeader("resultcode", "6");
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(e);
}
response.setHeader("resultcode", "7");
} finally {
if (null != bis)
bis.close();
if (null != fos)
fos.close();
}
}
private void uploadFile() throws IOException
{
if (log.isDebugEnabled())
{
log.debug("outdir:" + outdir.getPath());
log.debug("outfile:" + outfile.getPath());
}
if (!outdir.exists())
outdir.mkdir();
if (!outfile.exists())
outfile.createNewFile();
fos = new FileOutputStream(outfile);
int i;
while ((i = bis.read(bs)) != -1)
{
fos.write(bs, 0, i);
}
}
public static String getDatedFName(String fname) {
StringBuffer result = new StringBuffer();
SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
String dateSfx = "_" + df.format(new Date());
int idx = fname.lastIndexOf('.');
if (idx != -1) {
result.append(fname.substring(0, idx));
result.append(dateSfx);
result.append(fname.substring(idx));
} else {
result.append(fname);
result.append(dateSfx);
}
return result.toString();
}
public static String getUrlFName(String fname, HttpServletRequest request) {
String result = "";
if (isEmpty(fname)) return result;
try {
if (fname.startsWith("https://")) {
result = fname;
} else {
String ip = request.getServerName();
int port = request.getServerPort();
result = fname.substring(fname.indexOf(UploadFileServlet.SBPATH));
StringBuffer tmpBuff = new StringBuffer();
tmpBuff.append("https://").append(ip).append(":").append(port).append(OBLIQUE_LINE).append(result);
result = tmpBuff.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("result is: "+result);
return result;
}
public static boolean isEmpty(String str) {
return ((str == null) || (str.length() == 0));
}
private String getRealDir(String newFileNameRoot) throws Exception {
if (newFileNameRoot == null)
throw new Exception("get real dir failed !");
int dp = newFileNameRoot.lastIndexOf(OBLIQUE_LINE);
if (dp == -1)
throw new Exception("invalid path !");
int dpbefore = newFileNameRoot.lastIndexOf( OBLIQUE_LINE, dp - 1);
if (dpbefore == -1)
throw new Exception("invalid path !");
String needSubStr = newFileNameRoot.substring(dpbefore + 1, dp);
String nextStr = newFileNameRoot.substring(0, dpbefore + 1);
if (!needSubStr.trim().equals(WEBPOSITION)) {
return getRealDir(nextStr);
} else
return newFileNameRoot;
}
public static void main(String[] args)
{
}
}
與之配套的 web.xml 配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="https://java.sun.com/xml/ns/j2ee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee
https://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>com.hemi.rhet.servlet.UploadFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/system/fileUpload</url-pattern>
</servlet-mapping>
</web-app>