寫一個(gè)servlet或jsp來接收,在servlet或jsp處理業(yè)務(wù)邏輯,后返回處理結(jié)果或新的數(shù)據(jù)
創(chuàng)新互聯(lián)于2013年成立,先為高昌等服務(wù)建站,高昌等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為高昌企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
如jsp:
%@ page errorPage="/common/error/error.jsp" %
%@ page contentType="text/html;charset=GBK"%
%
String planeNumber = request.getParameter("planeNumber");
String planeType = com.aerolink.aocs.system.parameter.list.PlaneTypeFactory.getPlaneType(planeNumber);
response.getWriter().write(planeType);%
android客戶端代碼:
public class MainActivity extends Activity
{
private TextView uploadInfo;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadInfo = (TextView) findViewById(R.id.upload_info);
uploadFile();
}
public void uploadFile()
{
//服務(wù)器端地址
String url = "";
//手機(jī)端要上傳的文件,首先要保存你手機(jī)上存在該文件
String filePath = Environment.getExternalStorageDirectory()
+ "/1/power.apk";
AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams param = new RequestParams();
try
{
param.put("file", new File(filePath));
param.put("content", "liucanwen");
httpClient.post(url, param, new AsyncHttpResponseHandler()
{
@Override
public void onStart()
{
super.onStart();
uploadInfo.setText("正在上傳...");
}
@Override
public void onSuccess(String arg0)
{
super.onSuccess(arg0);
Log.i("ck", "success" + arg0);
if(arg0.equals("success"))
{
Toast.makeText(MainActivity.this, "上傳成功!", 1000).show();
}
uploadInfo.setText(arg0);
}
@Override
public void onFailure(Throwable arg0, String arg1)
{
super.onFailure(arg0, arg1);
uploadInfo.setText("上傳失?。?);
}
});
} catch (FileNotFoundException e)
{
e.printStackTrace();
Toast.makeText(MainActivity.this, "上傳文件不存在!", 1000).show();
}
}
}
服務(wù)器端代碼:
public class UploadFileServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// 創(chuàng)建文件項(xiàng)目工廠對(duì)象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設(shè)置文件上傳路徑
String upload = this.getServletContext().getRealPath("/upload/");
// 獲取系統(tǒng)默認(rèn)的臨時(shí)文件保存路徑,該路徑為Tomcat根目錄下的temp文件夾
String temp = System.getProperty("java.io.tmpdir");
// 設(shè)置緩沖區(qū)大小為 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 設(shè)置臨時(shí)文件夾為temp
factory.setRepository(new File(temp));
// 用工廠實(shí)例化上傳組件,ServletFileUpload 用來解析文件上傳請(qǐng)求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
// 解析結(jié)果放在List中
try
{
ListFileItem list = servletFileUpload.parseRequest(request);
for (FileItem item : list)
{
String name = item.getFieldName();
InputStream is = item.getInputStream();
if (name.contains("content"))
{
System.out.println(inputStream2String(is));
} else if(name.contains("file"))
{
try
{
inputStream2File(is, upload + "\\" + item.getName());
} catch (Exception e)
{
e.printStackTrace();
}
}
}
out.write("success");
} catch (FileUploadException e)
{
e.printStackTrace();
out.write("failure");
}
out.flush();
out.close();
}
// 流轉(zhuǎn)化成字符串
public static String inputStream2String(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1)
{
baos.write(i);
}
return baos.toString();
}
// 流轉(zhuǎn)化成文件
public static void inputStream2File(InputStream is, String savePath)
throws Exception
{
System.out.println("文件保存路徑為:" + savePath);
File file = new File(savePath);
InputStream inputSteam = is;
BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
int f;
while ((f = fis.read()) != -1)
{
fos.write(f);
}
fos.flush();
fos.close();
fis.close();
inputSteam.close();
}
}
.服務(wù)器端
package sterning;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
int port = 8821;
void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 選擇進(jìn)行傳輸?shù)奈募?/p>
String filePath = "D:\\lib.rar";
File fi = new File(filePath);
System.out.println("文件長(zhǎng)度:" + (int) fi.length());
// public Socket accept() throws
// IOException偵聽并接受到此套接字的連接。此方法在進(jìn)行連接之前一直阻塞。
s = ss.accept();
System.out.println("建立socket鏈接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//將文件名及長(zhǎng)度傳給客戶端。這里要真正適用所有平臺(tái),例如中文名的處理,還需要加工,具體可以參見Think In Java 4th里有現(xiàn)成的代碼。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意關(guān)閉socket鏈接哦,不然客戶端會(huì)等待server的數(shù)據(jù)過來,
// 直到socket超時(shí),導(dǎo)致數(shù)據(jù)不完整。
fis.close();
s.close();
System.out.println("文件傳輸完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String arg[]) {
new ServerTest().start();
}
}
2.socket的Util輔助類
package sterning;
import java.net.*;
import java.io.*;
public class ClientSocket {
private String ip;
private int port;
private Socket socket = null;
DataOutputStream out = null;
DataInputStream getMessageStream = null;
public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}
/** *//**
* 創(chuàng)建socket連接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}
public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}
public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}
public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {
}
}
}
3.客戶端
package sterning;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class ClientTest {
private ClientSocket cs = null;
private String ip = "localhost";// 設(shè)置成服務(wù)器IP
private int port = 8821;
private String sendMessage = "Windwos";
public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("連接服務(wù)器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("連接服務(wù)器失敗!" + "\n");
return false;
}
}
private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("發(fā)送消息失敗!" + "\n");
}
}
private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息緩存錯(cuò)誤\n");
return;
}
try {
//本地保存路徑,文件名會(huì)自動(dòng)從服務(wù)器端繼承而來。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;
savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();
System.out.println("文件的長(zhǎng)度為:" + len + "\n");
System.out.println("開始接收文件!" + "\n");
while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面進(jìn)度條本為圖形界面的prograssBar做的,這里如果是打文件,可能會(huì)重復(fù)打印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存為" + savePath + "\n");
fileOut.close();
} catch (Exception e) {
System.out.println("接收消息錯(cuò)誤" + "\n");
return;
}
}
public static void main(String arg[]) {
new ClientTest();
}
}
新聞名稱:java文件接收代碼,上傳文件java代碼
網(wǎng)頁(yè)URL:http://aaarwkj.com/article18/dsiedgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、網(wǎng)站營(yíng)銷、云服務(wù)器、定制網(wǎng)站、用戶體驗(yàn)、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)