android 上传文件

android端:

private String photoPath = Configuration.SD_CARD_PATH + "/123.jpg";
public void uploadFile2Svr() {
long l = System.currentTimeMillis();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(_URL + "uploadFile");

String uploadMsg = "上传 照片失败!";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// Your DATA
nameValuePairs.add(new BasicNameValuePair("filename", ("IMAGE.jpg")) );
// nameValuePairs.add(new BasicNameValuePair("orderno", "1"));
// nameValuePairs.add(new BasicNameValuePair("userid", "123"));
// nameValuePairs.add(new BasicNameValuePair("attach_type", "1"));
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

File aFile = new File(photoPath);
Log.i("System.out", "info -- photoPath: " + photoPath);
FileEntity fileEty = new FileEntity(aFile, "binary/octet-stream");
httppost.setEntity(fileEty);
httppost.addHeader("filename", aFile.getName());

HttpResponse response;
response = httpclient.execute(httppost);
//Log.i("info -- response: ", response.getStatusLine().getReasonPhrase());

Header[] headers = response.getAllHeaders();
headers = response.getHeaders("resultcode");
if (headers[0].getValue().equals("0")) {
uploadMsg = "上传照片成功!";
}

} catch (UnsupportedEncodingException e) {
//e.printStackTrace();
uploadMsg += e.toString();
Log.e("System.out", e.toString());
} catch (ClientProtocolException e) {
//e.printStackTrace();
uploadMsg += e.toString();
Log.e("System.out", e.toString());
} catch (IOException e) {
//e.printStackTrace();
uploadMsg += e.toString();
Log.e("System.out", e.toString());
} finally {
Log.i("System.out", "uploadMsg = " + uploadMsg);
httpclient.getConnectionManager().shutdown();
Log.e("System.out", "time = " + (System.currentTimeMillis() - l));
}
}

private void uploadFile2Svr2() {
BufferedReader in = null;

HttpClient httpclient = new DefaultHttpClient();

URL url = null;
try {
url = new URL(_URL + "uploadFile");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}

HttpURLConnection conn = null;
DataOutputStream dos = null;

String lineEnd = "/r/n";
String twoHyphens = "--";
String boundary = "*****";
int maxBufferSize = 16 * 1024;

try {
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//// Your DATA
// nameValuePairs.add(new BasicNameValuePair("filename", getDatedFName("IMAGE.jpg")) );
// nameValuePairs.add(new BasicNameValuePair("orderno", "1"));
// nameValuePairs.add(new BasicNameValuePair("userid", "123"));
// nameValuePairs.add(new BasicNameValuePair("attach_type", "1"));
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(120000);

// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);

// Use a post method.
conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type",
//"multipart/form-data;boundary=" + boundary);
"application/x-www-form-urlencoded");

conn.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 GTB6");
//conn.setRequestProperty("accept-language", "zh-cn,zh;q=0.5");
//conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);

conn.connect();

//OutputStream connOs = conn.getOutputStream();
dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename=""
+ "exsistingFileName" + """ + lineEnd);
//dos.writeBytes(lineEnd);

Log.i("System.out", "Headers are written");

// upload file to webserver via http
FileInputStream fileInputStream = new FileInputStream(photoPath);
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];

// read file and write it into form...

int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams
Log.e("System.out", "File is written");
fileInputStream.close();

dos.flush();
dos.close();
dos = null;

// response
// HttpResponse response;
// response = httpclient.execute(httppost);
// response = httpclient.execute(conn.get);

in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.i("System.out", result);

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(in != null){
try{
in.close();
}catch(IOException ioe){
Log.e("System.out", ioe.toString());
}
}
}
}

 

servlet:
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;

private void doUplaodFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String root = this.getServletContext().getRealPath("/");
root = root.replaceAll("////", "/");

try
{
StringBuffer destFName = new StringBuffer();
// destFName.append(getRealDir(root)).append(SBPATH);
destFName.append("/mnt/sdcard/").append(SBPATH);
outdir = new File(destFName.toString());

request.setCharacterEncoding("UTF-8");

uploadFName = request.getParameter("filename"); //name of uploaded file
uploadFName = request.getHeader("filename");
if (isEmpty(uploadFName)) uploadFName = "filename.jpg";
//orderNo = request.getParameter("orderno"); //id of the order or work sheet
//userId = request.getParameter("userid"); //id of the user who upload the file
//attachType = request.getParameter("attach_type"); //type of attachment, refer to file.FileBean's definition

String desc = request.getParameter("desc"); //description of uploaded file
if (desc==null) desc = "";

if (true)
{
destFName.append(getDatedFName(uploadFName));
outfile = new File(destFName.toString());

bis = new BufferedInputStream(request.getInputStream());
uploadFile();

//response.getWriter().write("0"); //success
response.setHeader("resultcode", "0");

}
else if (desc.length() > 400/2) {
//response.getWriter().write("3"); //illegal description
response.setHeader("resultcode", "3");
}
else
{
System.out.println("调用格式错误!");
response.sendError(100, "参数错误!");
//response.getWriter().write("1");
response.setHeader("resultcode", "1"); //parameter error

//return;
}
} catch (Exception e) {
//response.getWriter().write("7"); //failure
response.setHeader("resultcode", "7");
e.printStackTrace();
} finally {
if (null != bis)
bis.close();
if (null != fos)
fos.close();
}
}

private void uploadFile() throws IOException
{
System.out.println("outdir:" + outdir.getPath());
System.out.println("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("http://")) {
result = fname;
} else {
//HttpServletRequest request = ServletActionContext.getServletContext().getRgetRequest();
//UserAndOrganAndRole user = (UserAndOrganAndRole)request.getSession().getAttribute("user");

String ip = request.getServerName();
int port = request.getServerPort();

result = fname.substring(fname.indexOf(SBPATH));
StringBuffer tmpBuff = new StringBuffer();
tmpBuff.append("http://").append(ip).append(":").append(port).append(OBLIQUE_LINE).append(result);
//Sample: http://localhost:8083/UploadedFiles/IMAGE_067_100222102521.jpg

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)) {



原文地址:https://www.cnblogs.com/shanzei/p/2434508.html