/*
* ====================================================================
*作者:aixushuai
*
*用httpclient模拟一个form表单 上传一个文件到另一个服务端
*/
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
* maven依赖的jar包,如下
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.4</version>
</dependency>
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
String serverURL = "http://localhost/mypoject/uploadAttachment";
String path = "D://test//tt.png";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverURL);
// 默认的的ContentType是application/octet-stream
FileBody bin = new FileBody(new File(path));
// FileBody bin = new FileBody(new File(path), ContentType.create("image/png"));
// 其他文本类型的参数
StringBody eamil = new StringBody("test@test.com", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sourcefiles", bin).addPart("email", eamil).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务器相应状态码----------------------------------------" + statusCode);
if (statusCode == HttpStatus.SC_OK) {
System.out.println("服务器正常返回的数据: " + EntityUtils.toString(resEntity));// httpclient自带的工具类读取返回数据
System.out.println(resEntity.getContent());
} else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
System.out.println("上传文件发生异常,请检查服务端异常问题");
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
python中django请求接收文件:
def uploadAttachment(request):
print request
# if 'sourcefiles' in request.POST:
if True:
sourcefiles = request.FILES['sourcefiles']
email = request.POST.get('email','')
print 'sourcefiles.content_type----------------->',sourcefiles.content_type
if sourcefiles.content_type == 'application/octet-stream' or sourcefiles.content_type == 'image/jpeg' or sourcefiles.content_type == 'application/x-jpg' or sourcefiles.content_type == 'image/png' or sourcefiles.content_type == 'application/x-png' or sourcefiles.content_type == 'text/plain':
_contentList = handle_uploaded_file(sourcefiles)
file_path = save_uploaded_file(sourcefiles, email)
data = {'file_path':file_path}
else:
data = {'error':'没有选择上传文件'}
a = simplejson.dumps(data)
return HttpResponse(a, 'application/javascript')
def save_uploaded_file(sourcefiles, email):
now = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d-%H-%M-%S')
filename = sourcefiles.name + "_" + email + "_" + now
filePath = "/home/project/myproject" + STATIC_URL + "/attachment/" + filename
print filePath
destination = open(filePath, 'wb+')
try:
for chunk in sourcefiles.chunks():
print "----------->", chunk
destination.write(chunk)
except Exception, e:
print "save_uploaded_file----%s : %s" % (Exception, e)
finally:
destination.close()
return filePath