上传不了图片,帮我找一下错
//-----------UploadThread ---------------
public class UploadThread extends Thread {
private String fileName;
private String url;
public UploadThread(String fileName,String url) {
// TODO Auto-generated constructor stub
this.url=url;
this.fileName=fileName;
}
@Override
public void run() {
String boundary = "---------------------------7e130613d0e3a";
String prefix = "--";
String end = "\r\n";
try {
URL HttpUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) HttpUrl
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","multipart/form-data;boundary="+ boundary); // 通过 multipart
DataOutputStream out=new DataOutputStream(connection.getOutputStream()) ; // 协议向服务器发送数据
out.writeBytes(prefix+boundary+end);
out.writeBytes("Content-Description:form-data;"+"name=\"file\";filename=\""+"Sky.jpg"+"\""+end);
out.writeBytes(end);
FileInputStream fileInputStream=new FileInputStream(new File(fileName));
byte[]b=new byte[1024*4];
int len;
while((len=fileInputStream.read(b))!=-1){
out.write(b,0,len);
}
out.writeBytes(end);
out.writeBytes(prefix+boundary+prefix+end);
out.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sbBuffer=new StringBuffer();
String str;
while((str=reader.readLine())!=null){
sbBuffer.append(str);
}
System.out.println("------respose:"+sbBuffer.toString());
if (out!=null) {
out.close();
}
if (reader!=null) {
reader.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//----------------UploadActivity-----------------------
public class UploadActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://172.16.166.195:8080/Upload/";
File file = Environment.getExternalStorageDirectory();
File fileAbs = new File(file, "sky.jpg");
String fileName = fileAbs.getAbsolutePath();
UploadThread thread = new UploadThread(fileName, url);
thread.start();
}
});
}
}ps:权限都加了的