IIS / ASP.NET - Request.Files在生产中空

时间:2014-04-15 20:08:42

标签: android asp.net

我正在使用Android手机的HTTP POST将文件上传到ASP.NET ASPX页面。当使用的Web服务器是开发服务器(Visual Studio 2013,IIS Express)时,该过程非常有效。 Request.Files集合包含我的文件,所有这些都与世界一致。

在IIS 7.5下运行的相同代码仍然返回200的响应代码(不是405!),但Request.Files集合完全为空。

对于我的生活,我无法弄清楚为什么。如果动词被拒绝,我应该收到405代码。

这是在手机上执行的Java代码:

URL postURL = new URL("redacted");

// Create the HTTP connection set our properties.
conn = (HttpURLConnection) postURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "text/plain");
conn.setRequestProperty("uploaded_file", file.getName());

// Set up our stream writer.
dos = new DataOutputStream(conn.getOutputStream());

// Write the opening.
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="
    + file.getName() + ";filename=" + file.getName()
    + ";Content-Type: text/plain" + lineEnd);

dos.writeBytes(lineEnd);

// Grab our file and the stream object.
fileInputStream = new FileInputStream(file);

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

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

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

// Finish up writing our file.
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Close our stream objects.
fileInputStream.close();
dos.flush();
dos.close();

IIS中是否存在一些我不知道会阻止数据传播的设置?我看过的每个例子都是使用HTTP POST从Android上传文件而没有Apache库,看起来就像这样。

1 个答案:

答案 0 :(得分:0)

我明白了。看来,IIS 7.5在请求属性时并不像IIS Express那样宽松。

我做了以下更改:

// conn.setRequestProperty("Content-Type", "text/plain"); 
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);  

//dos.writeBytes("Content-Disposition: form-data; name="     + file.getName() + ";filename=" + file.getName()     + ";Content-Type: text/plain" + lineEnd); 
dos.writeBytes("Content-Disposition: form-data; name=\"" + file.getName() + \";filename=\"" + file.getName() + "\"" + lineEnd);

我自己测试了每个变化,但它不会起作用。为了让页面在IIS 7.5下获取,我必须在将文件写入流时在文件名周围加上引号,并且我的内容类型必须更改。